关于html:尝试渲染按钮控件时,Angular innerHTML属性不起作用

Angular innerHTML property not working while try to render button control

我已经创建了角度应用程序。在这里,我想使用[innerHTML]属性注入一些内容,如下所示

1
2
3
4
5
6
7
8
export class AppComponent  {
  name = 'Angular';
  public bar = 'bars';
  foo = ``+this.bar+`
 
  <button type="button" onclick="alert('Hello world!')">Click Me!</button>
`;
}

我已经在如下的html文件中使用了此功能

1
 

但我只是简单地只返回div元素。 按钮控件未呈现。

我创建了一个stackb示例供您参考。 请提供任何想法如何做

sample - https://stackblitz.com/edit/angular-ena2xj?file=src/app/app.component.ts

参考-Angular HTML绑定


您应该使用DomSanitizer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { Component } 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 sanitized: DomSanitizer) {}

   name = 'Angular';
  public bar = 'bars';
  foo = this.sanitized.bypassSecurityTrustHtml( ``+this.bar+`
 
  <button type="button" onclick="alert('Hello world!')">Click Me!</button>
`);
}


您可以将其更改为@ViewChild,

像这样更改您的ts文件,

1
2
3
4
5
6
7
8
9
export class AppComponent  {
  @ViewChild('someVar') el:ElementRef;
  name = 'Angular';
  public bar = 'bar';
  ngAfterViewInit() {
  this.el.nativeElement.innerHTML = ``+this.bar+`
  <button type="button" onclick="alert('Hello world!')">Click Me!</button>`;
}
}

工作Stackblitz https://stackblitz.com/edit/angular-vnk9ft