2016-12-05 49 views
0

我對這個和角度2還是比較新的。我感覺到我要問你的是非常重要的,但我無法把頭繞在它身上。所以我有一個我們稱之爲容器包含子組件的組件,你可以瀏覽過類似:打字稿事件子對家長

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

您指定事件在父組件的處理方法和$事件作爲參數傳遞給處理器來傳遞什麼發出。