Angular2 父子组件通讯

Angular2 中父子组件之间通讯分别通过 @Input 和 @Output 实现。假设父子组件结构如下:

parent.component.html
1
2
3
4
<parent>
<h1>{{childProp}}</h1>
<child [parent2child]="i" (childEmitter)="child2parent($event)"></child>
</parent>

1、父组件 -> 子组件

  • 父组件通过属性将变量发送给子组件。
  • 子组件使用 @Input 装饰器接收父组件传入的变量。
父组件:
parent.component.ts
1
2
3
4
5
6
7
8
9
10
11
@Component({
selector: 'parent',
templateUrl: 'parent.component.html',
styleUrls: [
'parent.component.scss',
]
})

export class ParentComponent {
i:number = 1;
}
子组件:
child.component.ts
1
2
3
4
5
6
7
8
9
10
11
12
import {Component, Input} from 'angular2/core';

@Component({
selector: 'child',
template: `
<h2>child {{parent2child}}</h2>
`
})

export class ChildComponent {
@Input() parent2child: number;
}

2、子组件 -> 父组件

  • 子组件使用 @Output 装饰器注册一个发射器(Emitter),通过该发射器发送变量。
  • 父组件通过监听事件来接收变量。
子组件:
child.component.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import {Output, EventEmitter, Component} from 'angular2/core';

@Component({
selector: 'child',
template: `
<h2>child</h2>
`
})

export class ChildComponent {
@Output() childEmitter:EventEmitter<number> = new EventEmitter();

childProp:number = 0;

this.childEmitter.emit(this.childProp);
}
父组件:
parent.component.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Component({
selector: 'parent',
templateUrl: 'parent.component.html',
styleUrls: [
'parent.component.scss',
]
})

export class ParentComponent {
childProp:number = 0;

child2parent(childProp:number){
this.childProp = childProp;
}
}