【问题标题】:Adding event handler for element from raw HTML为原始 HTML 中的元素添加事件处理程序
【发布时间】:2021-05-17 06:25:07
【问题描述】:

应用程序从外部 API 获取原始 HTML 字符串,我需要呈现这些数据。还应添加span id="sp1"click 事件的处理程序。

看完文章后:

我正在尝试使用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>

它不起作用:

  1. 点击“获取 API 数据”按钮。
  2. 点击“测试”标签。
  3. “TEST clicked”文本未显示在控制台中。

我错过了什么?

【问题讨论】:

    标签: html angular element


    【解决方案1】:

    你必须等到 DomSanitizer.bypassSecurityTrustHtml 更新真实的 DOM 后才能搜索元素,例如:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多