单击事件在 innerhtml 字符串中不起作用 angular 6

click event is not working in innerhtml string angular 6

我正在使用 angular 6 生成动态模板。我有一个 API return 字符串,如下所示:

    <button type="button" (click)="openAlert()">click me</button>

和html

    <div [innerHtml]="myTemplate | safeHtml">
      </div>

函数如下:

    openAlert() {
        alert('hello');
      }

基本上这样不行。当你在Angular里面写代码的时候,被webpacktranspiled转换成javascript在浏览器中执行

但是,现在您正在动态注入 Angular code 而不是 build 注入。事件检测 (click) 不会在本机工作,函数 openAlert 也不在它被注入的全局范围内。您将不得不考虑一种不同的方法,并根据 API.

的响应使用 <ng-template> 生成内容

您不能将 angular 事件直接绑定到 innerHTML。

如果您需要附加事件侦听器,则需要在加载 html 内容后进行。

一旦内容被设置为变量,ngAfterViewInit Angular 生命周期事件将被触发。这里需要附加需要的事件监听器。

检查下面的工作示例。

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));
    }
  } 
}

安全-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);
    }

}

这应该也有效:

component.html

<div #template></div>

component.ts

@ViewChild('template') myTemplate: ElementRef;

addTemplate(){
   this.myTemplate.nativeElement.innerHTML = '<button type="button">click me</button>';
   this.myTemplate.nativeElement.addEventListener('click', this.openAlert);
}