2017-09-03 68 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"; 
    } 
}