Reputation: 1031
I have a web component that emits a CustomEvent
to notify other components about a tenant change of the user.
this.dispatchEvent(new CustomEvent('tenant-changed', {
detail: {
tenant: newTenant
},
bubbles: true,
composed: true
}));
I want to use this web component in an Angular 6 application. I tried to register for the CustomEvent
, but somehow the Angular component does not get notified. I tried the following two approaches
ngOnInit() {
this.renderer.listen(this.elementRef.nativeElement, 'tenant-changed', (event) => {
this.changeTenant(event);
})
this.elementRef.nativeElement.queryElement('#my-filter').addEventListener('tenant-changed', this.changeTenant.bind(this));
}
Or isn't this approach possible at all?
Upvotes: 0
Views: 3118
Reputation: 911
It's also possible to use Angular's Event Binding Mechanism to listen to a Web Component's dispatched events.
In your case it will look like this:
app.component.html
<app-filter (tenant-changed)="onTentantChanged($event)"></app-filter>
app.component.ts
onTentantChanged(event: CustomEvent){
// do something spectacular!
}
Upvotes: 1
Reputation: 1031
I found the answer to my problem. First I have to use window.dispatchEvent
instead of this.dispatchEvent
.
Then it is easy in Angular to listen to this event using a regular event listener: window.addEventListener('tenant-changed, this.changeTenant.bind(this))
Upvotes: 3