Angular2如何在组件代码中订阅事件?(Angular2 How to subscribe to event in Component code?)

编程入门 行业动态 更新时间:2024-10-08 13:38:44
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

更多推荐

本文发布于:2023-08-07 13:21:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464044.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组件   事件   代码   如何在   event

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!