angular 将字符串作为html元素插入

angular为了安全的原因,默认不会直接将字符串作为html文本显示,如果想作为文本显示,可以使用innerHTML属性插入。
但是插入之前需要对字符串进行过滤,以保证安全性,可以使用以下两种方法。

一、直接处理插入

如果处理的地方不多的话,可以在每一个组件中进行处理

import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { DomSanitizer, SafeHtml } from "@angular/platform-browser";

@Component({
  selector: 'app-content',
  template: `
    <span [innerHTML]="safeHtml"></span>
    <p>content works!</p>
  `,
  styles: [],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ContentComponent implements OnInit {
  safeHtml: SafeHtml = '';
  htmlString = '<span style="background-color: chartreuse">i am a test text!</span>'

  constructor(private sanitizer: DomSanitizer) {}

  ngOnInit(): void {
    this.safeHtml = this.sanitizer.bypassSecurityTrustHtml(this.htmlString)
  }
}

二、使用管道处理

如果处理的地方比较多,可以创建管道,使用管道进行处理

创建管道

创建命令就不解释了

ng g pipe pipe/safeHtml --skip-tests

管道文件内容

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml } from "@angular/platform-browser";

@Pipe({name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform {
  constructor(private sanitized: DomSanitizer) {
  }

  transform(value: string): SafeHtml {
    return this.sanitized.bypassSecurityTrustHtml(value)
  }

}

组件文件进行调用

import { ChangeDetectionStrategy, Component } from '@angular/core';

@Component({
  selector: 'app-content',
  template: `
    <span [innerHTML]="htmlString | safeHtml"></span>
    <p>content works!</p>
  `,
  styles: [],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ContentComponent {
  htmlString = '<span style="background-color: chartreuse">i am a test text!</span>'
}
posted @ 2023-02-07 11:28  cos1eqlg0  阅读(243)  评论(0编辑  收藏  举报