Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 dispatchEvent with custom event

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?

like image 209
Batsheva Avatar asked Jul 25 '17 08:07

Batsheva


2 Answers

Your event is not bubbling. Try it:

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

Plunker Example

like image 140
yurzui Avatar answered Nov 18 '22 19:11

yurzui


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>();
  
}
like image 27
Poul Kruijt Avatar answered Nov 18 '22 20:11

Poul Kruijt