You cannot bind angular events directly to innerHTML.
Still if you need to attach the event listeners you need to to do it after the html content is loaded.
Once the content is set to the variable, ngAfterViewInit Angular life cycle event will be triggered. Here you need to attach the required event listeners.
Checkout the working example below.
component.html
<button (click)="addTemplate()">Get Template</button>
<div [innerHTML]="myTemplate | safeHtml"></div>
component.ts
import { Component, ElementRef } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
myTemplate = '';
constructor(private elementRef:ElementRef){
}
openAlert() {
alert('hello');
}
addTemplate(){
this.myTemplate = '<button type="button" id="my-button" (click)="openAlert()">click mee</buttn>';
}
ngAfterViewChecked (){
if(this.elementRef.nativeElement.querySelector('#my-button')){
this.elementRef.nativeElement.querySelector('#my-button').addEventListener('click', this.openAlert.bind(this));
}
}
}
safe-html.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({
name: 'safeHtml'
})
export class SafeHtmlPipe implements PipeTransform {
constructor(private sanitized: DomSanitizer) {}
transform(value) {
return this.sanitized.bypassSecurityTrustHtml(value);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…