Batsheva
Batsheva

Reputation: 669

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?

Upvotes: 9

Views: 37156

Answers (2)

Poul Kruijt
Poul Kruijt

Reputation: 71911

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>();
  
}

Upvotes: 2

yurzui
yurzui

Reputation: 214057

Your event is not bubbling. Try it:

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

Plunker Example

Upvotes: 18

Related Questions