innerHTML对于某些标签(例如按钮或自定义标签)不起作用

Aks*_*arg 2 html javascript angular

当我通过角度插值分配一些html标签(如按钮)或自定义标签时插值出现问题,但未显示

在component.html文件中

<div [innerHTML]="html"></div>

在component.ts文件中

html = "<h1>Header</h1> <button>Button</button>"

无法在有角https://stackblitz.com/edit/angular-j5gsb4?embed=1&file=app/app.component.ts中工作

它在纯html / js中工作 https://plnkr.co/edit/3PWexJjKbOEe50egKjqJ?p=preview

voi*_*oid 5

innerHTML 不是公开为HTML元素的属性的属性。

<div [innerHTML]="html"></div>
Run Code Online (Sandbox Code Playgroud)

所以这行不通。

您可以@ViewChild用来访问DOM元素

app.component.html

<div #someVar></div>
Run Code Online (Sandbox Code Playgroud)

app.component.ts

import {ElementRef} from '@angular/core';
@ViewChild('someVar') el:ElementRef;

constructor() {}

ngAfterViewInit() {
      this.el.nativeElement.innerHTML = "some html";
}
Run Code Online (Sandbox Code Playgroud)

  • 这个答案没有任何意义。 (2认同)