angular输出带有style样式的html

问题描述:要使用angular获取一个HTML格式且含有style样式的字符串javascript

首先,angular输出html格式的字符串(note)的实现方法为:html

<div [innerHTML]="note" ></div>

可是,运行代码后发现,这样并不可以将note字符串中的style样式显示出来。java

angular输出带有style样式的html格式的字符串的实现方法为:ionic

1.自定义一个HtmlPipe类ide

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.在须要的模块中引入管道HtmlPipethis

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文本。