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

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

问题描述

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

 

和 html

 

功能如下:

 openAlert() {警报('你好');}

解决方案

不能将 Angular 事件直接绑定到 innerHTML.

如果您需要附加事件监听器,您需要在加载 html 内容后执行此操作.

一旦将内容设置为变量,ngAfterViewInit Angular 生命周期事件就会被触发.您需要在此处附加所需的事件侦听器.

查看下面的工作示例.

component.html

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

component.ts

import { Component, ElementRef } from '@angular/core';@成分({选择器:'我的应用',templateUrl: './app.component.html',styleUrls: ['./app.component.css']})导出类 AppComponent {name = '角度';我的模板 = '';构造函数(私有元素引用:元素引用){}打开警报(){警报('你好');}添加模板(){this.myTemplate = '

safe-html.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';从'@angular/platform-b​​rowser' 导入 { DomSanitizer };@管道({名称:'safeHtml'})导出类 SafeHtmlPipe 实现 PipeTransform {构造函数(私有消毒:DomSanitizer){}变换(值){返回 this.sanitized.bypassSecurityTrustHtml(value);}}

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>

and html

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

function is bellow:

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

解决方案

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

}

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

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