[英]Angular2+ how to let child get notification from parent
对于Angular2 +,我们可以使用@output通知父对象,是否有任何方法可以让孩子知道在发出Child事件之前或之后调用了哪个父函数?
下面是父HTML代码,它将调用子组件以执行onClick或OnClose函数。
<child-comp (test1)="onClick()">
...
</child-comp>
<child-comp (test2)="onClose()">
...
</child-comp>
以下是子代码。
@Component({
selector: 'child-comp'
})
export class ChildComponent{
@Output() test1: EventEmitter<any> = new EventEmitter();
@Output() test2: EventEmitter<any> = new EventEmitter();
handleClick() {
//this.test1.emit("test1 is emitted");
//or
//this.test2.emit("test2 is emitted");
}
}
问题是test1和test2都在handleClick函数中,一旦发出test1或test2事件,如何让孩子知道执行哪个父函数?
向子项添加一个@Input()属性whatHappendInParent,并编写如下内容:
<child-comp (test1)="onClick()" [whatHappenedInParent] = whatHappened>
...
</child-comp>
<child-comp (test2)="onClose()" [whatHappenedInParent] = whatHappened>
...
</child-comp>
...
export class myParent {
whatHappened: string;
onClick(){
this.whatHappened = "onClick was called";
}
onClose(){
this.whatHappened = "onClose was called";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.