angular 使用[innerHTML]在页面中显示html文本

在ts文件模拟一个html文本:

  1. import { Component, OnInit } from '@angular/core';
  2. @Component({
  3.   selector: 'app-inner-html',
  4.   templateUrl: './inner-html.component.html',
  5.   styleUrls: ['./inner-html.component.css']
  6. })
  7. export class InnerHtmlComponent implements OnInit {
  8.   constructor() { }
  9.   content = '<span>'+
  10.   '<strong>'+
  11.   '<span style="font-size: 50px;color:red">'+
  12.   '把啦啦啦'+
  13.   '</span>'+
  14.   '</strong>'+
  15.   '</span>'
  16.   ngOnInit() {
  17.   }
  18. }

html文件:

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

这时在页面上就会出现

但是发现原本在html文本中设置的style样式都不见了 我们需要添加一个pipe

先创建一个pipe文件:

  1. import {Pipe, PipeTransform} from "@angular/core";
  2. import {DomSanitizer} from "@angular/platform-browser";
  3. @Pipe({
  4. name: "html"
  5. })
  6. export class HtmlPipe implements PipeTransform{
  7. constructor (private sanitizer: DomSanitizer) {
  8. }
  9. transform(style) {
  10. return this.sanitizer.bypassSecurityTrustHtml(style);
  11. }
  12. }

然后在app.module中引入一下:

import { HtmlPipe } from \'./inner-html/innerhtmlpipe\';
  1. @NgModule({
  2. declarations: [
  3.     ...
  4. HtmlPipe,
  5.     ...
  6. ],

最后在html文件中使用:

<div [innerHTML]="content | html"></div>

这是页面上的文字就会出现style样式了

作者:该用户已成仙

来源:https://blog.csdn.net/qq_39785489/article/details/79850530


如果给你带来帮助,欢迎微信或支付宝扫一扫,赞一下。