Angular2 中父子组件之间通讯分别通过 @Input 和 @Output 实现。假设父子组件结构如下:
parent.component.html
1 | <parent> |
1、父组件 -> 子组件
- 父组件通过属性将变量发送给子组件。
- 子组件使用
@Input
装饰器接收父组件传入的变量。
父组件:
parent.component.ts
1 | @Component({ |
子组件:
child.component.ts
1 | import {Component, Input} from 'angular2/core'; |
2、子组件 -> 父组件
- 子组件使用
@Output
装饰器注册一个发射器(Emitter),通过该发射器发送变量。 - 父组件通过监听事件来接收变量。
子组件:
child.component.ts
1 | import {Output, EventEmitter, Component} from 'angular2/core'; |
父组件:
parent.component.ts
1 | @Component({ |