How to create and fire a custom event in angular

GJCode picture GJCode · May 20, 2019 · Viewed 15.5k times · Source

I'm new in Angular and I've read about event binding so I can do something like this:

<button (click)="doSomething()"></button>

I'd like to know if it's possible to create a custom event and do the same thing. Let's say that I want to have a custom event like: deleteItem, is it possible to do something like this? And how?

<my-component (deleteItem)="doSomething()"></my-component>

Answer

Ehsan Kiani picture Ehsan Kiani · May 20, 2019

Of course, you can use an eventEmitter in my-component ts file add this

 @Output() deleteItem= new EventEmitter();

and when you want to rise the event do this

  this.deleteItem.emit();

also you can pass data like this

  this.countUpdate.emit({value: some data });

then catch it in the parent component like this

<my-component (deleteItem)="doSomething($event)"></my-component>

and in the parent ts file

    doSomething(event)
    { 
       console.log(event);
    }