【发布时间】: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>
它不起作用:
- 点击“获取 API 数据”按钮。
- 点击“测试”标签。
- “TEST clicked”文本未显示在控制台中。
我错过了什么?
【问题讨论】: