2016-02-01 117 views
3

我已經實現了選項卡,我在那裏有一個表格& tab1中的一個按鈕。我在父組件中有一個事件,它使當前選項卡無效並激活下一個選項卡。如何從子組件中調用父組件中的事件?如何從子組件中調用父組件中的事件?

gotosecondtab(){ 
this.firsttabactive=false; 
this.secondtabactive=true; 
} 

這是父組件的事件......我想,當我執行的onsubmit()事件運行從子組件

onSubmit(): void { 
console.log('you submitted value: ', this.myForm.value); 
//How to call the parent event here 
} 

我想運行gotosecondtab()事件此事件.. .Somebody幫我請

回答

5

你可以在你的子組件創建自定義事件

@Component({ 
    selector: 'child', 
    (...) 
}) 
export class ChildComponent { 
    @Output() myevent: EventEmitter; 

    constructor() { 
    this.myevent = new EventEmitter(); 
    } 

    onSubmit(): void { 
    console.log('you submitted value: ', this.myForm.value); 
    this.myevent.emit(); 
    } 
} 

- >(myevent)

@Component({ 
    template: ` 
    <child (myevent)="gotosecondtab()"></child> 
    `, 
    directives: [ ChildComponent ] 
    (...) 
}) 
export class ParentComponent { 
    (...) 

    gotosecondtab() { 
    } 
} 

希望它能幫助, 蒂埃裏

+1

在我的項目,我必須要在模板添加到回調函數$事件參數:從父組件上註冊=「gotosecondtab($ event) – loose11

+1

是的,如果你想爲你觸發的事件提供一個值(調用'emit'作爲參數)。我沒有看到'gotosecondtab'方法的任何參數。這就是爲什麼我沒有使用'$ event' ;-) –

+0

我不想發送任何參數,所以$事件不是必需的......感謝Thierry Templier –

相關問題