Angular 6-将事件处理程序添加到动态创建的html元素中 [英] Angular 6 - Add Event handler to dynamically created html element

查看:286
本文介绍了Angular 6-将事件处理程序添加到动态创建的html元素中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将click事件附加到动态创建的html元素上. click事件应该能够触发组件中的另一种方法.

I want to attach a click event to the dynamically created html element. The click event will should be able to fire another method in component.

我已经经历过其他建议使用ElementRef附加事件的答案.但是,它不适用于我的情况.

I have already gone through other SO answers suggesting to use ElementRef to attach event. But, its not working for my case.

我正在使用mapQuest API渲染地图.地图将标有地理编码&它将添加滚动内容.要添加过渡内容,我正在使用mapQuest的API方法,例如info.setInfoContentHTML('<a>click me</a>');

I am using mapQuest API to render map. The map will have geocode plotted & it will add a roll over content. To add the rollover content I am using the API method of mapQuest, like info.setInfoContentHTML('<a>click me</a>');

仅供参考: https://developer.mapquest.com/documentation/javascript-api/pois-infowindows/

链接将位于弹出窗口内,当用户将鼠标悬停在图标上时,该窗口会由插件动态添加到dom中.如何在仅当用户将鼠标悬停在&上时显示的链接上添加事件监听器插件没有提供回调事件,该事件可以在显示悬停弹出窗口后触发.

The link will be inside the popup which will be added to the dom dynamically by plugin when user hover on the icon. How to add event listener on the link which is shown only when the user hover over & there is no callback event provided by plugin which can fire after hover popup is displayed.

我一直在寻找类似jQuery的功能,尽管该元素不在DOM上,但该功能将附加事件侦听器.

I was looking for jQuery live like functionality which would attach event listener though the element is not on the DOM.

推荐答案

因为编译组件时Angular会处理模板. 以后添加的任何HTML都不会再次编译,并且绑定将被忽略.

Because Angular processes the template when the component is compiled. Any HTML added later is not compiled again and bindings are ignored.

您可以使用以下内容:

constructor(private elRef:ElementRef) {}

ngAfterViewInit() {
  // assume dynamic HTML was added before
  this.elRef.nativeElement.querySelector('button').addEventListener('click', 
  this.onClick.bind(this));
}

您的用例:

public createElement(){

  const el = '<button>click me</button>';
  this.elRef.nativeElement.querySelector('button').addEventListener('click', 
  this.methodName.bind(this));
  info.setInfoContentHTML(el);
}

public methodName(){

      console.log('burrah!!! called');
    }

这篇关于Angular 6-将事件处理程序添加到动态创建的html元素中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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