从 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>
在HTML代码中,有一个带参数的click事件。 (click)="Onclick(abc)"
现在我动态地添加它。 因此,点击事件无效。
我已经搜索了很多但却无法找到解决方案。 我的打字稿代码如下。
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);
}
我收到了这个错误。
ERROR TypeError: Cannot read property 'addEventListener' of null
但点击事件未触发。我已尝试使用SetTimeOut()
函数,间隔为3秒。
编辑: -
我正在检查,
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));
}
我得到了query_selector_value - null
答案 0 :(得分:0)
请尝试使用此行,同时检查以确保此类只有一个元素:
this.elementRef.nativeElement.querySelector("[class='click_for_save']")
.addEventListener('click', this.click_for_save.bind(this));
还要尝试这个以查看是否有多个具有相同类的元素:
var button = document.querySelector("[class='click_for_save']");
console.log(button);
查看它是否有任何元素。
更新:
试试这个
$("body").on("click", ".click_for_save", function(){
//do something
});