Angular2如何在组件代码中订阅事件?(Angular2 How to subscribe to event in Component code?)
我有一个带有Output事件的[boolean]指令:
@Output() booleanChanged = new EventEmitter(); ... this.booleanChanged.emit(value);在我看来:
<input type="checkbox" [boolean] (booleanChanged)="updateBoolean()"/>我想从组件的代码订阅此事件,而不是在视图中订阅。
有办法吗?
I have a [boolean] directive with an Output event:
@Output() booleanChanged = new EventEmitter(); ... this.booleanChanged.emit(value);And in my view:
<input type="checkbox" [boolean] (booleanChanged)="updateBoolean()"/>I would like to subscribe to this event from the component's code and not in the view.
Is there a way to do so?
最满意答案
@Output()事件只能由(myoutput)="..."绑定使用。
您可以发出自定义DOM事件。 DOM事件会冒泡,可以从父组件中侦听
class BooleanDirective { constructor(private elRef:ElementRef){} emitEvent() { final event = new CustomEvent('mycustomevent', {detail: 'abc', bubbles : true}); this.elRef.nativeElement.dispatchEvent(event) } }@HostListener('mycustomevent', ['$event']) myCustomEventHandler(event) { ... }另请参见angular2手动触发特定元素上的click事件
@Output() events can only be used by (myoutput)="..." bindings.
You could emit a custom DOM event. DOM events bubble and can be listened to from parent components
class BooleanDirective { constructor(private elRef:ElementRef){} emitEvent() { final event = new CustomEvent('mycustomevent', {detail: 'abc', bubbles : true}); this.elRef.nativeElement.dispatchEvent(event) } }@HostListener('mycustomevent', ['$event']) myCustomEventHandler(event) { ... }See also angular2 manually firing click event on particular element
更多推荐
发布评论