innerHTML在某些标签(如button或自定义标签)上不起作用。

25 浏览
0 Comments

innerHTML在某些标签(如button或自定义标签)上不起作用。

这个问题已经有答案了:

Angular HTML绑定

当我使用angular插值分配一些HTML标签(如按钮)或自定义标签时,插值无法显示。

在组件.html文件中:

在组件.ts文件中:

html = \"

Header

\"

在Angular中无法工作。

https://stackblitz.com/edit/angular-j5gsb4?embed=1&file=app/app.component.ts

在纯html/js中可以工作。

https://plnkr.co/edit/3PWexJjKbOEe50egKjqJ?p=preview

admin 更改状态以发布 2023年5月23日
0
0 Comments

默认情况下,Angular会对潜在的不安全内容进行安全处理。
您可以告诉Angular相信您的内容

import { DomSanitizer } from '@angular/platform-browser';
export class AppComponent  {
  constructor(private sanitizer:DomSanitizer){
    this.html = sanitizer.bypassSecurityTrustHtml("

Header

"); } html; }

StackBlitz示例

还可以参见https://stackoverflow.com/a/41089093/217408

0
0 Comments

innerHTML不是HTML元素的属性之一,也不会被公开作为属性。


所以这不起作用。

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

app.component.html


app.component.ts

import {ElementRef} from '@angular/core';
@ViewChild('someVar') el:ElementRef;
constructor() {}
ngAfterViewInit() {
      this.el.nativeElement.innerHTML = "some html";
}

0