问题描述:要使用angular获取一个HTML格式且含有style样式的字符串
首先,angular输出html格式的字符串(note)的实现方法为:
<div [innerHTML]="note" ></div>
但是,运行代码后发现,这样并不能够将note字符串中的style样式显示出来。
angular输出带有style样式的html格式的字符串的实现方法为:
1.自定义一个HtmlPipe类
import {Pipe, PipeTransform} from "@angular/core";
import {DomSanitizer} from "@angular/platform-browser";
@Pipe({
name: "html"
})
export class HtmlPipe implements PipeTransform{
constructor (private sanitizer: DomSanitizer) {
}
transform(style) {
return this.sanitizer.bypassSecurityTrustHtml(style);
}
}
2.在需要的模块中引入管道HtmlPipe
import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { HtmlInfoPage } from './html-info';
import {EmptyViewComponentModule} from "../../../components/empty-view/empty-view.module";
import {HtmlPipe} from "../../../providers/pipe";
@NgModule({
declarations: [
HtmlInfoPage,
HtmlPipe
],
imports: [
IonicPageModule.forChild(HtmlInfoPage),
EmptyViewComponentModule
],
exports: [
HtmlInfoPage
]
})
export class HtmlInfoPageModule {}
3.在innerHTML中增加管道名称
<div [innerHTML]="note | html" ></div>
这样就能够显示含有style样式的HTML文本。