如何添加点击事件动态添加打字稿中的html元素 [英] How to add click event to dynamically added html element in typescript

查看:113
本文介绍了如何添加点击事件动态添加打字稿中的html元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个角度为2的应用程序。我想为点击事件添加一个动态添加的html元素。
我定义了一个字符串(contentString),并且在这个字符串中我定义了html元素。

  var contentString =' < b>'+ this.mName +'< / b>< br /> '+ this.mObject.category +'< br />点击此处查看更多信息<按钮(click)=navigate()>浏览此处< / button>'; 

这个字符串放在一个html元素中,像这样:

  var boxText = document.createElement(div); 
boxText.innerHTML = contentString;

尽管当我检查元素时,它定义了click事件,但它不会触发。 / p>





on click it console log

  navigate(){
console.log(eeeehnnananaa) ;
}

但这不起作用。
任何解决方案?

解决方案

Angular在编译组件时处理模板。

您可以使用

 构造函数(private elRef:ElementRef){} 

ngAfterViewInit(){
//假设动态HTML被添加到
之前this.elRef.nativeElement.querySelector('按钮')。addEventListener('click',this.onClick.bind(this));
}


I'm building an app in angular 2. I want to add a click event to a dynamically added html element. I define a string (contentString), and in this string I define the html element.

var contentString = '<b>' + this.mName + '</b><br/> ' + this.mObject.category + '<br/> Click here for more information <button (click)="navigate()">Navigate here</button>'; 

This string is put inside a html element like this:

var boxText = document.createElement("div");
    boxText.innerHTML = contentString;

Although when I inspect the element, it has the click event defined, but it does not trigger.

on click it should console log

navigate() {
console.log("eeeehnnananaa");
}

But that does not work. Anyone a solution?

解决方案

Angular processes the template when the component is compiled. HTML added later is not compiled anymore and bindings are ignored.

You can use

constructor(private elRef:ElementRef) {}

ngAfterViewInit() {
  // assume dynamic HTML was added before
  this.elRef.nativeElement.querySelector('button').addEventListener('click', this.onClick.bind(this));
}

这篇关于如何添加点击事件动态添加打字稿中的html元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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