通过事件绑定来监听子组件的通知(暂且叫通知吧)
使用@output修饰器
父组件命名app-parent
子组件命名app-child
在子组件app-child中定义出口事件:
//引入组件
import {Output, EventEmitter} from '@angular/core';
export class ChildComponent implements OnInit {
...
//定义出口事件
@Output() result = new EventEmitter<string>();
//定义出口事件的触发事件
add(){
this.result.emit('add');//注意这字符串add的类型有new EventEmitter<string>内的string类型决定
}
}
//app-child模板
<button (click)="add()">加1</button>
在父组件app-parent的html中引用子组件
<app-child (result)="onCal($event)"></app-child>
onCal(result: string) {
console(result); //打印add
}
将@output修饰器注释的属性理解是一个类似click的事件,只是这个类似click的事件是由子组件的事件来触发