Angular 4 dispatchEvent with custom event

My requirement is to fire an event from code to the parent hosting component.

I used the first answer here as a link: angular2 manually trigger a click event on a specific element

If I try this it works well:

this.itemHost.viewContainerRef.element.nativeElement.dispatchEvent(new Event('click'));

      

In the parent component, I wrote the following:

(click)="go()"

      

It comes to the go method when the code above happens.

But it doesn't work if I do it with some custom event name like:

this.itemHost.viewContainerRef.element.nativeElement.dispatchEvent(new Event('customEvent'));

      

and in the parent component:

(customEvent)="go()"

      

How do I do this using a custom event?

+5


source to share


2 answers


Your event doesn't bubble up. Try:

.dispatchEvent(new Event('customEvent', { bubbles: true }));

      



Plunger example

+10


source


Use @Output()

to create custom events inside your components. In the example below, it fires when you click on it div

, but you can obviously emit it every time. Try to avoid using it nativeElement

as much as possible, as this will prevent your application from running in any other environment, but the browser

parent

@Component({
   selector: 'parent',
   template: `<child (customEvent)="onCustomEvent($event)"></child>
})
export class ParentComponent {

  onCustomEvent(response: string): void {
    console.log(response);
  }
}

      



child

@Component({
   selector: 'child',
   template: `<div (click)="customEvent.emit('blabla')"></div>
})
export class ChildComponent {

  @Output()
  customEvent: EventEmitter<string> = new EventEmitter<string>();

}

      

+1


source







All Articles