从动态添加的超链接调用 angular 函数
Calling angular function from dynamically added hyperlink
我正在向我的页面动态添加一些 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)
);
}
或者,您也可以使用 Renderer2
的 listen
method or HostListener
来绑定事件处理程序。
我正在向我的页面动态添加一些 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)
);
}
或者,您也可以使用 Renderer2
的 listen
method or HostListener
来绑定事件处理程序。