Firing events from dynamically added html

2019-07-15 01:20发布

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

}

2条回答
可以哭但决不认输i
2楼-- · 2019-07-15 02:07

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.

查看更多
Evening l夕情丶
3楼-- · 2019-07-15 02:16

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.

查看更多
登录 后发表回答