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?
Your event is not bubbling. Try it:
.dispatchEvent(new Event('customEvent', { bubbles: true }));
Plunker Example
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>();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With