[英]click event is not firing on dynamically generated elements
HTML Code which is dynamically added on DOM from. 从中动态添加到DOM的 HTML代码。
<ul>
<li>
<button (click)="Onclick(abc)" class="btn btn-sm btn-danger click_for_save pull-right" type="button">
<i class="fa fa-close"></i> Save </button>
</li>
</ul>
Here in HTML code there is a click event with parameters. 在HTML代码中,这里有一个带有参数的click事件。 (click)="Onclick(abc)"
Now I'm addind it dynamically. 现在,我动态添加它。 So, click event is not working. 因此,点击事件不起作用。
I have search a lot for it but not able to find the solution for it. 我为此进行了大量搜索,但无法找到解决方案。 My typescript code is below. 我的打字稿代码如下。
import { AfterViewInit, Component, ElementRef} from '@angular/core';
constructor(private elementRef:ElementRef) {}
// Below code I have added just after the dynamically added code.
this.elementRef.nativeElement.querySelector('.click_for_save')
.addEventListener('click', this.click_for_save.bind(this));
Onclick(abc) {
console.log(abc);
}
I'm getting this error. 我收到此错误。
ERROR TypeError: Cannot read property 'addEventListener' of null
But click event is not firing. 但是点击事件没有触发。 I have tried even with SetTimeOut()
function with 3 second gap. 我什SetTimeOut()
尝试了SetTimeOut()
函数,间隔为3秒。
EDIT :- 编辑:-
I'm checking with this, 我正在检查
let query_selector_value = this.elementRef.nativeElement.querySelector('.click_for_save');
if(query_selector_value){
query_selector_value.addEventListener('click', this.click_for_save.bind(this));
}
And I'm getting query_selector_value - null
我正在获取query_selector_value - null
Try this line instead, also inspect to make sure there is only one element with this class: 尝试使用此行,还要检查以确保此类中只有一个元素:
this.elementRef.nativeElement.querySelector("[class='click_for_save']")
.addEventListener('click', this.click_for_save.bind(this));
Also try this to see if there is more than one element with same class: 还可以尝试这样做以查看是否存在多个具有相同类的元素:
var button = document.querySelector("[class='click_for_save']");
console.log(button);
See if it has any elements. 看看是否有任何元素。
UPDATE: 更新:
Try this one 试试这个
$("body").on("click", ".click_for_save", function(){
//do something
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.