Reputation: 1252
Is it possible to bind to an event which is from external content. Content is brought in via innerHTML
I have the below code whereby I grab external content and display it within my app. I'm trying to listen to an onClick event for the <a>
tag. The <a>
is a route redirect. The listen should reside within my app as I want do some other things before routing to a new route.
I've tried setting a handleClick function but I don't think this is the correct way to do it.
I also thought maybe using a ElementRef
- in this case #view
but would jquery light be better in this case.
@Component({
selector: 'overview-details',
template: `
<h2>{{ title }}</h2>
<div #view [innerHTML]="regCode | sanitizeHtml"></div>
`
})
ngOninit() {
this.regcode = `
<div>
<h1>RegCode Content</h1>
<a class="link" (click)="handleClick()">Link</a>
</div>
`;
}
//within controller
handleClick(){
// do some stuff
// then route
router.navigate([somewhere....]);
}
Upvotes: 0
Views: 1501
Reputation: 1252
I worked out the following in the end.
I added the (click)
to the div
and also added a data-route
to the <a>
and can use event.target.dataset.route
to get the value.
Just incase anyone else has similar issues
@Component({
selector: 'overview-details',
template: `
<h2>{{ title }}</h2>
<div (click)="handleClick($event)" [innerHTML]="regCode | sanitizeHtml"></div>
`
})
ngOninit() {
this.regcode = `
<div>
<h1>RegCode Content</h1>
<a class="link" data-route="0">Link</a>
</div>
`;
}
handleClick(event: any) {
console.log('fire', event.target.dataset.route);
if (event.target.dataset.route == 0) {
router.navigate([somewhere....]);
} esle {
router.navigate([somewhereElse....]);
}
}
Upvotes: 1
Reputation: 657376
Angular doesn't process HTML added with [innerHTML]="..."
or any other way. Bindings like (click)="..."
work only when added statically to a comopnents template.
You can use
constructor(private elRef:ElementRef) {}
ngAfterViewInit() {
this.elRef.nativeElement.querySelector('a.link').addEventListener('click', this.handleClick.bind(this));
}
Upvotes: 1