对于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事件,如何让孩子知道哪个父函数被执行?
答案 0 :(得分:0)
将@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";
}
}