从动态添加的HTML触发事件 [英] Firing events from dynamically added html
问题描述
我必须从服务器上加载HTML数据,就像我点击了"一样
i have to load Html data from server like i have 'click'
但是当我将此数据分配给angular2中的innerHtml属性时,它显示的是html,但单击甚至无法正常工作.
but when i assign this data to innerHtml property in angular2 it shows html but click even is not working .
这个问题有解决方案吗?
is there any solution for this problem.
有一些使用动态组件的建议,但我找不到任何有关angular2最终发行版的好教程.
there are some suggestions to use dynamic Components but i don't find any good tutorial for final angular2 release.
import { Component, ViewChild, ElementRef, OnInit, Directive } from '@angular/core';
import { HttpComponent} from './http.component';
import {DomSanitizer, SafeHtml} from '@angular/platform-browser';
@Component({
moduleId: module.id,
selector: 'my-app',
template: `<div [innerHTML]="myVal"></div>`
})
export class AppComponent {
myVal: string = '<div><button onClick="showdata()"> Show Data </button></div>';
constructor(){}
showdata(){
console.log("test");
}
}
推荐答案
如果以这种方式分配点击处理程序,它将不会引用Angulars组件中的showdata()
,而是引用window.showdata()
. Angular不了解onclick
,onclick
不了解Angular.
If you assign a click handler this way, it won't refer to the showdata()
in Angulars component but for window.showdata()
. Angular doesn't know about onclick
and onclick
doesn't know about Angular.
我建议您将HTML添加到组件中,然后查询元素并使用添加事件处理程序
I would suggest you add the HTML to the component, then query for the element and add an event handler using
constructor(private elRef:ElementRef) {}
ngAfterViewInit() {
this.elRef.nativeElement.querySelector('button').addEventHandler('click', this.showdata.bind(this);
}
ngAfterViewInit()
可能不是正确的代码位置,具体取决于添加HTML的时间.
While ngAfterViewInit()
might not be the right place for the code, depending on when the HTML is added.
这篇关于从动态添加的HTML触发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!