2017-08-10 93 views
1

绑定HTML代码串我有HTML代码的组件变量象下面这样:对角2模板

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'/>"; 
} 

它显示等的输出“嗨伙计!”但是没有文本框。如何使用组件变量显示文本框绑定?

+0

如果您检查它,它会在浏览器中显示什么? –

+0

在浏览器中检测没有文本框ctrl代码,只是“嗨

dude
” –

回答

2

此代码不安全。所以,渲染输入元素默认是不允许的。您需要使用DomSanitizer允许它:

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

见,说明这个plunker sample

-1

在模板中,尝试:

<div [innerHTML]="name"> 
    <input type='text'/> 
</div> 

,并从名称中删除变量输入的标签。如果你想要数据绑定,请考虑在输入标签上使用ngModel。