2017-09-03 71 views
0

对于Angular2 +,我们可以使用@output来通知父母,有没有什么办法让孩子知道在发生Child事件之前或之后调用哪个父母函数?Angular2 +如何让孩子从父母得到通知

下面是父代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"); 

    } 
} 

的问题是,在这两个测试1和测试2在handleClick功能,一旦TEST1或TEST2事件发出的,如何让孩子知道被执行,父函数?

+0

你想知道,如果父订阅'test1'或'test2'?你实际上试图解决什么问题?您可以放出两者,父母决定使用哪一个。 –

+0

我想你是与事件发射器混淆勾选此[链接](https://rahulrsingh09.github.io/AngularConcepts/inout) –

回答

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"; 
    } 
}