Calling angular function from dynamically added hyperlink

喜你入骨 提交于 2021-02-08 12:09:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!