问题
I wanted to bind a function into the injected html at run time using innerHTML. My component
@Component({
selector: 'my-app',
template: `<div [innerHtml]="myHTML | safeHtml"></div>`,
styleUrls: ['/my-app.css'], encapsulation: ViewEncapsulation.ShadowDom
})
export class MyApp implements OnInit {
myHTML = `<button (click)="clickMe()" type="button" class="btn btn-secondary">+</button>`
constructor() {}
clickMe() {
console.log("Function is binded using the inner html tag")
}
}
I tried but it does not seem to work. I am not sure if I have missed something. Any help is appreciated
回答1:
Implement safeHtml
pipe; it does not come out of box:
@Pipe({
name: 'safeHtml'
})
export class SafeHtmlPipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) { }
transform(value: string): any {
return this.sanitizer.bypassSecurityTrustHtml(value);
}
}
来源:https://stackoverflow.com/questions/54615567/bind-a-function-with-the-injected-html-in-angular-7