javascriptangularweb-componentangular-elementsangular-event-emitter

Listen to Angular web component EventEmitter into javascript


I have a created a small web component with the help of this article using angular element which includes @Input and @Output.

I am able to pass data to @Input property but listening to the @Output event is making me crazy as I am unable to figure out how to read data from the callback event parameter.

//Emitting the boolean data
likeEvent() { 
    this.likeNotify.emit(true);
}

And in pure javascript I am listening to likeNotify event like this:

const el = document.querySelector('facebook-card');
      el.addEventListener('likeNotify', e => {
        console.log(e.currentTarget.data); // Not working
      });

So How can I retrieve true/false value from e object passed from emitter?


Solution

  • The data transmitted through the Output in a web-component can be read from the event.detail property:

    const el = document.querySelector('facebook-card');
    
    el.addEventListener('likeNotify', (event) => console.log(event.detail));
    

    For more details you can read here

    Component outputs are dispatched as HTML Custom Events, with the name of the custom event matching the output name. For example, for a component with @Output() valueChanged = new EventEmitter(), the corresponding custom element will dispatch events with the name "valueChanged", and the emitted data will be stored on the event’s detail property. If you provide an alias, that value is used; for example, @Output('myClick') clicks = new EventEmitter<string>(); results in dispatch events with the name "myClick".