2017-01-18 24 views
1

テンプレートを経由せずに、親のtypescriptファイルに直接データを出力したい入れ子コンポーネントがあります。 使用できません<child (childEvent)="parentFunc()"></child>角2:子コンポーネントから親コンポーネントのスクリプトファイルに直接送信

これは可能ですか?もしそうなら、どうですか?

これは現在の状態です。

parent.component.html(要素このなければならない)

<child #child> </child> 

parent.component.ts

@ViewChild('child') public child; 

public doSomething() { 
    this.child.work(); 
} 

public doThisWhenChildEmits(someData) { 
    //?????How do I call this function from child without going through the DOM 
    alert(It worked) 
} 

child.component.ts

あなたが使用しない場合は3210

答えて

1

@Outputあなたの代わりにSubjectを使用することもできます。

あなたの親が変更にサブスクライブします。あなたの親には、コンポーネントで件名を宣言し、コンストラクタの変化を購読する:

public static changesMade: Subject<any> = new Subject(); 

//inside constructor the following 
ParentComponent.changesMade.subscribe(res => { 
    //call your method here, with the res (someData) you receive from child 
    this.doThisWhenChildEmits(res); 
}); 

とあなたの子供で:

public clickToSendBack(){ 
    // send the data to parent 
    ParentComponent.changesMade.next(someData) 
} 

このことができますなら、私を知ってみましょう! :)

+0

ありがとうございます。私はあなたの答えがうまくいくと思う、私はそれにコミットし、最高の答えとしてあなたを選択する前にカップル日を与えたい。 –

+0

本当に、分かります! :) – Alex

関連する問題