Firing events from dynamically added html

久未见 提交于 2019-12-12 19:25:09

问题


i have to load Html data from server like i have 'click'

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.

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");
    }

}

回答1:


My proposal is to use JavaScript to listen the click event and get the element by id:

component:

ngOnInit() {
    var myVal = document.getElementById("myVal");
    myVal.innerHTML = '<div><button id="btn"> Show Data </button></div>'; 
    document.getElementById("btn").addEventListener("click", function(){
        console.log("Button clicked, do something.");
});
}

template:

<div id="myVal"></div>

Its working for me.




回答2:


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.

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);
}

While ngAfterViewInit() might not be the right place for the code, depending on when the HTML is added.



来源:https://stackoverflow.com/questions/40063791/firing-events-from-dynamically-added-html

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