ng-content内的渲染按钮失败

时间:2018-04-09 10:20:00

标签: angular

我正在尝试在angular5中使用ng-content。我的标签有一个简单的html5按钮,我想渲染它。但是在渲染后没有显示为按钮。

请看看这个松弛。 slack

1 个答案:

答案 0 :(得分:1)

您不要像这样使用<ng-content>。如果你想要转换内容,你可以把它放在元素标签之间,就像这样(我要保留你的元素名称):

<app-comp1>
  <button type="button">Click Me!</button>
</app-comp1>

如果您确实需要渲染html字符串,则需要注入DomSanitizer并使用bypassSecurityTrustHtml方法。像这样:

app.component.html

<app-comp1>
  <div [innerHTML]="safeStr"></div>
</app-comp1>

app.component.ts

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 {
  str1 = `
    <button type="button">Click Me!</button>
  `
  constructor(private sanitizer: DomSanitizer) { }

  get safeStr() {
    return this.sanitizer.bypassSecurityTrustHtml(this.str1);
  }

}

Live demo

相关问题