Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

javascript - click event is not working in innerhtml string angular 6

I am working on an generate dynamic template using angular 6. I have an API that return strings like below:

    <button type="button" (click)="openAlert()">click me</button>

and html

    <div [innerHtml]="myTemplate | safeHtml">
      </div>

function is bellow:

    openAlert() {
        alert('hello');
      }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You cannot bind angular events directly to innerHTML.

Still if you need to attach the event listeners you need to to do it after the html content is loaded.

Once the content is set to the variable, ngAfterViewInit Angular life cycle event will be triggered. Here you need to attach the required event listeners.

Checkout the working example below.

component.html

<button (click)="addTemplate()">Get Template</button>
<div [innerHTML]="myTemplate | safeHtml"></div>

component.ts

import { Component, ElementRef } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  myTemplate  = '';

  constructor(private elementRef:ElementRef){

  }
  openAlert() {
    alert('hello');
  }
  addTemplate(){
     this.myTemplate  = '<button type="button" id="my-button" (click)="openAlert()">click mee</buttn>';
  }
  ngAfterViewChecked (){
    if(this.elementRef.nativeElement.querySelector('#my-button')){
      this.elementRef.nativeElement.querySelector('#my-button').addEventListener('click', this.openAlert.bind(this));
    }
  } 
}

safe-html.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({
  name: 'safeHtml'
})
export class SafeHtmlPipe implements PipeTransform {
constructor(private sanitized: DomSanitizer) {}
  transform(value) {
        return this.sanitized.bypassSecurityTrustHtml(value);
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...