我有一个页面可以从API接收它的HTML内容。
在该代码中,有一些DIV与类#34; openMap"。 当用户点击这些DIV时,我希望执行一项功能(警告('是'),如下例所示)。
我尝试过以下但是
console.log(elementsWithClass[i]);
输出每个元素的HTML,我无法添加点击事件。
如何实现这一目标? 目前的代码:
this.http.get(httpGetUrl)
.subscribe(data => {
let returnedHtml = data['_body'];
if(returnedHtml != ''){
this.notdienstHtml = returnedHtml;
this.zone.run(() => {
let elementsWithClass = document.getElementsByClassName("openMap");
setTimeout(function(){
console.log(elementsWithClass.length);
for (let i=0; i < elementsWithClass.length; i++) {
console.log(elementsWithClass[i]); //correctly outputs HTML-content of each DIV it iterates over
elementsWithClass[i].onclick = function(){
//not run when DIV is clicked
alert('yes');
}
};
}, 300);
});
}
});
答案 0 :(得分:1)
尝试从将呈现响应的组件绑定事件。
import { AfterViewInit, Component, ElementRef} from '@angular/core';
constructor(private elementRef:ElementRef) {}
ngAfterViewInit() {
this.elementRef.nativeElement.querySelector('my-element')
.addEventListener('click', this.onClick.bind(this));
}
onClick(event) {
console.log(event);
}
答案 1 :(得分:0)
这就是我最终的结果。 重要的是,如果内容是动态的,请通过ts文件中的element.innerHtml更新,而不是使用html文件中的[innerHtml]。
HTML中的
<div #mainHtml id="mainHtml"></div>
在构造函数之前:
@ViewChild('mainHtml') mainHtml: ElementRef;
功能:
this.http.get(httpGetUrl)
.subscribe(data => {
let returnedHtml = data['_body'];
if(returnedHtml != ''){
let nativEl = this.mainHtml.nativeElement;
nativEl.innerHTML = returnedHtml; //update the HTML
let elements = nativEl.querySelectorAll('.openMap'); //openMap is the css selector
for(let element of elements){
element.addEventListener('click', this.openMap.bind(this)); //openMap is the function name
}
}
});