我的问题,当我使用innererHtml绑定时 - angular2删除所有样式属性.这对我来说很重要,因为在我的任务中 - html是在服务器端生成的,具有所有样式.例:
@Component({
selector: 'my-app',
template: `
<input type="text" [(ngModel)]="html">
<div [innerHtml]="html">
</div>
`,
})
export class App {
name:string;
html: string;
constructor() {
this.name = 'Angular2'
this.html = "<span style=\"color:red;\">1234</span>";
}
}
Run Code Online (Sandbox Code Playgroud)
但是在DOM中我只看到1234而且这个文本不是红色的.
http://plnkr.co/edit/UQJOFMKl9OwMRIJ38U8D?p=preview
谢谢!
yur*_*zui 124
你可以利用DomSanitized它来避免它.
最简单的方法是创建自定义管道,如:
import { DomSanitizer } from '@angular/platform-browser'
import { PipeTransform, Pipe } from "@angular/core";
@Pipe({ name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform {
constructor(private sanitized: DomSanitizer) {}
transform(value) {
return this.sanitized.bypassSecurityTrustHtml(value);
}
}
Run Code Online (Sandbox Code Playgroud)
所以你可以使用它:
<div [innerHtml]="html | safeHtml"></div>
Run Code Online (Sandbox Code Playgroud)
mve*_*and 33
我通过完成所需的导入改进了yurzui的例子:
import {DomSanitizer} from '@angular/platform-browser';
import {PipeTransform, Pipe} from "@angular/core";
@Pipe({ name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform {
constructor(private sanitized: DomSanitizer) {}
transform(value) {
return this.sanitized.bypassSecurityTrustHtml(value);
}
}
Run Code Online (Sandbox Code Playgroud)
我还必须在app.module.ts文件中添加该类
import ...
import {SafeHtmlPipe} from "./pipes/safehtml.pipe";
@NgModule({
declarations: [
AppComponent,
...,
SafeHtmlPipe <--
],
imports: [...],
providers: [...],
bootstrap: [AppComponent]
})
export class AppModule {
}
Run Code Online (Sandbox Code Playgroud)
请注意,sanitizer有几种方法可以信任内容,例如
return this.sanitizer.bypassSecurityTrustStyle(value);
return this.sanitizer.bypassSecurityTrustHtml(value);
return this.sanitizer.bypassSecurityTrustXxx(value); // - see docs [1]
Run Code Online (Sandbox Code Playgroud)
因此,这bypassSecurityTrustStyle可能也是您想要的,因为这将在HTML内容(value)中显示内联样式。
[1]文档:https : //angular.io/docs/ts/latest/api/platform-browser/index/DomSanitizer-class.html
| 归档时间: |
|
| 查看次数: |
40892 次 |
| 最近记录: |