Adam Shakhabov
Adam Shakhabov

Reputation: 1366

Adding event handler for element from raw HTML

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:

  1. Click the "Get API Data" button.
  2. Click the "TEST" label.
  3. "TEST clicked" text is not displayed in the console.

What am I missing?

Upvotes: 0

Views: 643

Answers (1)

H. Esambaev
H. Esambaev

Reputation: 36

You have to wait until DomSanitizer.bypassSecurityTrustHtml updates the real DOM before searching the element, for example:

getApiData() {
  // In prod the rawHtml value retrieved by external call
  var rawHtml = `<h2>What is Lorem Ipsum?</h2><span id="sp1">TEST</span>`;

  this.myHtml = this.sanitizer.bypassSecurityTrustHtml(rawHtml);
  setTimeout(() => {
    var elem = this.elementRef.nativeElement.querySelector('#sp1');
    if (elem) {
      elem.addEventListener('click', this.logInfo.bind(this));
    }
  }, 0)
}

Upvotes: 2

Related Questions