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

问题描述 投票:0回答:1

我正在向页面动态添加一些html。我添加了此

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

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

如果我将此html添加到组件模板中,一切正常。如何解决此问题?

angular function hyperlink click
1个回答
0
投票

Angular不了解动态添加的元素的事件。一种解决方法是使用ElementRefquerySelector函数添加事件处理程序。尝试以下操作

import { AfterViewInit, Component, ElementRef } from '@angular/core';

constructor(private elementRef: ElementRef) { }

ngAfterViewInit() {
  this.elementRef.nativeElement.querySelector('.image-fav').addEventListener(
    'click', this.imageDel.bind(this)
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.