从动态添加的超链接调用角度函数

问题描述:

我正在向页面动态添加一些html.我已经添加了

I'm adding some html dynamically to my page. I have add this

<a [routerLink]="[]" class="image-fav" (click)="imageDel()">CLICK-ME</a>

单击此超链接应调用imageDel函数,但不会这样做.

Click on this hyperlink should call the imageDel function but it does not do so.

如果我将此html直接添加到组件模板,则一切正常.我该如何解决这个问题?

If I add this html to component template straight everything works fine. How can I fix this problem ?

Angular无法理解动态添加元素的事件.一种解决方法是使用 ElementRef

Angular doesn't understand the events of dynamically added elements. One workaround would be to use ElementRef's querySelector function to add the event handler. Try the following

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 监听 方法或 HostListener 绑定事件处理程序.

Alternatively, you could also use Renderer2's listen method or HostListener to bind the event handler.