我正在向页面动态添加一些html。我添加了此
<a [routerLink]="[]" class="image-fav" (click)="imageDel()">CLICK-ME</a>
单击此超链接应调用imageDel函数,但不会这样做。
如果我将此html添加到组件模板中,一切正常。如何解决此问题?
Angular不了解动态添加的元素的事件。一种解决方法是使用ElementRef
的querySelector
函数添加事件处理程序。尝试以下操作
import { AfterViewInit, Component, ElementRef } from '@angular/core';
constructor(private elementRef: ElementRef) { }
ngAfterViewInit() {
this.elementRef.nativeElement.querySelector('.image-fav').addEventListener(
'click', this.imageDel.bind(this)
);
}