2016-12-05 10 views
0

私はまだこれと角度2でかなり新しいです。私はあなたに聞こうとしていることがかなり基本的だと感じていますが、私はそれの周りに私の頭を包むことはできません。typescriptイベント親から子へ

@Component({ 
    template:'<html> <router-outlet></router-outlet> </html>' 
}) 
export class ParentComponent implements OnInit{ 

    @ViewChild(childComponent) childComponent:ChildComponent; 
    constructor(){} 

    ngOnInit(){ 
     if(childComponent){ 
     childComponent.myEvent.subscribe(row=>this.test(row)); 
     } 
    } 


    test(row:any){ 
     alert("I Fired"); 
    } 
} 

@Component({ 
template:'<some html></some html>' 
}) 
export class ChildComponent implements OnInit{ 
    myEvent = new EventEmitter(); 
    constructor(){} 

    ngOnInit():void{ 
     this.myEvent.emit("some info"); 
    } 
} 

だから私が午前問題は親にそれがイベントchildComponentに加入しようとしたときということです。だから、私はあなたがあまりにものようなものをナビゲートすることができ、我々はそれが子コンポーネントが含まれているコンテナ呼び出すコンポーネントを持っています無効である。どんな助けもありがとう。ありがとうございました。

答えて

0

子イベントをサブスクライブするための方法は、テンプレートを通じてです:あなたがイベントに親コンポーネントでハンドラメソッドを指定し、放出されたものを渡すハンドラにパラメータとして$イベントを渡す

@Component({ 
    template:'<html> <router-outlet (myEvent)="test($event)"></router-outlet> </html>' <-- Add the (myEvent) event handling here 
}) 
export class ParentComponent implements OnInit{ 

    @ViewChild(childComponent) childComponent:ChildComponent; 
    constructor(){} 

    test(row:any){ 
     alert("I Fired"); 
    } 
} 

@Component({ 
    template:'<some html></some html>' 
}) 
export class ChildComponent implements OnInit{ 
    @Output() myEvent = new EventEmitter(); <-- Use @Output() here 
    constructor(){} 

    ngOnInit():void{ 
     this.myEvent.emit("some info"); 
    } 
} 

関連する問題