【问题标题】:Bind a function with the injected html in angular 7用Angular 7中注入的html绑定一个函数
【发布时间】:2019-07-04 01:30:00
【问题描述】:

我想在运行时使用 innerHTML 将一个函数绑定到注入的 html 中。 我的组件

@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")
  }
}

我试过了,但它似乎不起作用。我不确定我是否遗漏了什么。任何帮助表示赞赏

【问题讨论】:

标签: angular angular-directive


【解决方案1】:

实现safeHtml管道;它不是开箱即用的:

@Pipe({
  name: 'safeHtml'
})
export class SafeHtmlPipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) { }

  transform(value: string): any {
    return this.sanitizer.bypassSecurityTrustHtml(value);
  }
}

【讨论】:

    猜你喜欢
    • 2019-08-08
    • 2019-07-02
    • 2019-08-09
    • 1970-01-01
    • 2019-06-30
    • 2021-11-18
    • 2023-03-30
    • 2016-07-26
    • 1970-01-01
    相关资源
    最近更新 更多