click事件在innerhtml字符串angular 6中不起作用 [英] click event is not working in innerhtml string angular 6

查看:82
本文介绍了click事件在innerhtml字符串angular 6中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用angular 6生成动态模板.我有一个API,它返回如下字符串:

I am working on an generate dynamic template using angular 6. I have an API that return strings like below:

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

和html

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

功能如下:

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

推荐答案

您不能将角度事件直接绑定到innerHTML.

You cannot bind angular events directly to innerHTML.

仍然需要在加载HTML内容后附加事件侦听器.

Still if you need to attach the event listeners you need to to do it after the html content is loaded.

将内容设置为变量后,将触发ngAfterViewChecked Angular生命周期事件.在这里,您需要附加必需的事件侦听器.

Once the content is set to the variable, ngAfterViewChecked Angular life cycle event will be triggered. Here you need to attach the required event listeners.

查看下面的工作示例.

component.html

component.html

<button (click)="addTemplate()">Get Template</button>
<div [innerHTML]="myTemplate | safeHtml"></div>

component.ts

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

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

}

这篇关于click事件在innerhtml字符串angular 6中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆