首页 文章

在Angular 2模板上绑定HTML代码字符串

提问于
浏览
1

我在Component变量上有HTML代码,如下所示:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `Hi <div [innerHTML]="name"></div>`,
  styleUrls: ['./app.component.css'],
   styles: [`
    .highlight {
      background-color: yellow;
    }
  `],
})
export class AppComponent {
name :string ="dude ! <input type='text'/>";
}

它显示输出像“嗨伙计!”但那里没有文本框 . 如何使用组件变量显示文本框绑定?

1 回答

  • 3

    此代码不安全 . 因此,默认情况下不允许渲染输入元素 . 您需要使用DomSanitizer来允许它:

    constructor(sanitizer: DomSanitizer) {
      this.name = sanitizer.bypassSecurityTrustHtml( this.name);
    }
    

    请参阅说明这一点的plunker sample .

相关问题