3

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?

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
naomi
  • 2,583
  • 2
  • 22
  • 39

1 Answers1

1

@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

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567