2017-07-25 21 views
2

我的需求是從事件代碼觸發父宿主組件。有自定義事件的角4 dispatch事件

我這裏使用的第一個答案作爲參考:angular2 manually firing click event on particular element

如果我試試這個,它工作得很好:

this.itemHost.viewContainerRef.element.nativeElement.dispatchEvent(new Event('click')); 

在父組件我寫了這個:

(click)="go()" 

當上面的代碼出現時,它到達go方法。

但是,如果我有一些自定義的事件名稱做了,比如這不起作用:

this.itemHost.viewContainerRef.element.nativeElement.dispatchEvent(new Event('customEvent')); 

,並在父組件:我如何與自定義事件做

(customEvent)="go()" 

+0

你必須使用'Output()'裝飾器 – PierreDuc

+0

我試過了,並沒有成功。你能舉例說明如何申報嗎? – Batsheva

回答

7

您的活動不冒泡。試試看:

.dispatchEvent(new Event('customEvent', { bubbles: true })); 

Plunker Example

+0

非常棒!非常感謝! – Batsheva

+0

@Batsheva不客氣! – yurzui

+0

我也可以在這裏傳遞事件參數嗎? – Batsheva

1

使用@Output()有你的組件中自定義事件。在下面的例子中,它是在點擊div時被觸發的,但是你顯然可以隨時發出它。儘量避免使用nativeElement儘可能多的,因爲這將防止運行在任何其他環境中應用程序,但是瀏覽器

@Component({ 
    selector: 'parent', 
    template: `<child (customEvent)="onCustomEvent($event)"></child> 
}) 
export class ParentComponent { 

    onCustomEvent(response: string): void { 
    console.log(response); 
    } 
} 

孩子

@Component({ 
    selector: 'child', 
    template: `<div (click)="customEvent.emit('blabla')"></div> 
}) 
export class ChildComponent { 

    @Output() 
    customEvent: EventEmitter<string> = new EventEmitter<string>(); 

}