问题
I'm adding some html dynamically to my page. I have add this
<a [routerLink]="[]" class="image-fav" (click)="imageDel()">CLICK-ME</a>
Click on this hyperlink should call the imageDel function but it does not do so.
If I add this html to component template straight everything works fine. How can I fix this problem ?
回答1:
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)
);
}
Alternatively, you could also use Renderer2
's listen method or HostListener to bind the event handler.
来源:https://stackoverflow.com/questions/62108704/calling-angular-function-from-dynamically-added-hyperlink