从动态添加的超链接调用角度函数 [英] Calling angular function from dynamically added hyperlink

查看:94
本文介绍了从动态添加的超链接调用角度函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在向页面动态添加一些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.

这篇关于从动态添加的超链接调用角度函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆