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?

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

9 Comments

Is there a way to share this custom event in multiple directives?
What do you mean with "share" exactly?
I want to fire the same event from multiple directives (and subscribe once) is it enough to just use the same name like 'mycustomevent'?
Exactly. It's only about the event name string to match.
Sorry about that. You can just use var. I'm sure it will work. I don't use TypeScript myself, but expected it to work.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.