Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 How to subscribe to event in Component code?

Tags:

angular

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?

like image 318
naomi Avatar asked Mar 21 '26 20:03

naomi


1 Answers

@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

like image 70
Günter Zöchbauer Avatar answered Mar 23 '26 14:03

Günter Zöchbauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!