Angular 4 dispatchEvent with custom event

28,599

Solution 1

Your event is not bubbling. Try it:

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

Plunker Example

Solution 2

Use @Output() to have custom events inside your components. In the example below it is triggered while clicking on a div, but you can obviously have it emit whenever. Try to avoid the use of nativeElement as much as possible, because this will prevent running your application 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>();

}
Share:
28,599
Batsheva
Author by

Batsheva

Updated on July 09, 2022

Comments

  • Batsheva
    Batsheva almost 2 years

    My requirment is to fire event from the code to a parent hosting component.

    I used the first answer here as a reference: angular2 manually firing click event on particular element

    If I try this, it works well:

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

    In the parent component I wrote this:

    (click)="go()"
    

    It arrives to the go method when the above code occurs.

    But this doesn't work if I do it with some custom event name, e.g.:

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

    and in the parent component:

    (customEvent)="go()"
    

    How can I do it with custom event?