The application gets raw HTML string from external API and I need to render this data. Also handler for click event of span id="sp1" should be added.
After reading the articles:
I am trying to do it with the code below (StackBlitz):
app.component.ts
import { Component, ElementRef } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(
    private elementRef: ElementRef,
    private sanitizer: DomSanitizer
  ) {}
  myHtml;
  logInfo() {
    console.log('TEST clicked!');
  }
  getApiData() {
    // In prod the rawHtml value retrivied by external call
    var rawHtml = `<h2>What is Lorem Ipsum?</h2><span id="sp1">TEST</span>`;
    this.myHtml = this.sanitizer.bypassSecurityTrustHtml(rawHtml);
    var elem = this.elementRef.nativeElement.querySelector('#sp1');
    if (elem) {
      elem.addEventListener('click', this.logInfo.bind(this));
    }
  }
}
app.component.html
<div [innerHTML]="myHtml"></div>
<button (click)="getApiData()">Get API Data</button>
It does not work:
- Click the "Get API Data" button.
- Click the "TEST" label.
- "TEST clicked" text is not displayed in the console.
What am I missing?
 
    