如何编辑和渲染存储为字符串的内部 html?

How to edit and render inner html stored as a string?

我有一个来自字符串类型变量的 HTML 片段。 考虑,以下语句存储为字符串类型变量,

displayContent =
    `<div>
        <img alt="image1" src="image1.jpeg"/>
    </div>
    <div>
        <p>Some random text</p>
        <img alt="image2" src="image2.jpeg"/>
        <p>Some random text again</p>
        <img alt="image3" src="image3.jpeg"/>
        <p>Some random text</p>
    </div>`

现在,我必须在 HTML 页面中显示字符串变量 'displayContent',其中 'displayContent' 呈现为 html 文本。

我用过这个:<span [innerHTML]='displayContent'> 它在我的 HTML 主页面中精美地渲染了变量 'displayContent' 的 HTML 代码。

现在,某些来源的图片比我的页面大。我需要为每个 <img /> 添加样式元素,例如 <img style="max-width: 100%" />

为了实现这一点,我们可以简单地在 javascript 文件中使用 replace() 作为 displayContent = displayContent.replace(/<img/gi,'<img style="max-width: 100%" ')

所以,我们的新 'displayContent' 变成了

`<div>
    <img style="max-width: 100%" alt="image1" src="image1.jpeg"/>
</div>
<div>
    <p>Some random text</p>
    <img style="max-width: 100%" alt="image2" src="image2.jpeg"/>
    <p>Some random text again</p>
    <img style="max-width: 100%" alt="image3" src="image3.jpeg"/>
    <p>Some random text</p>
</div>`

现在,当我使用 <span [innerHTML]='displayContent'> 它不会以任何方式缩放我的图像。 图片仍然是原来的大小。

此外,浏览器的开发者工具中的图像样式属性没有更新。 Click here to see developer tools Styles

我找到了(也许)解决方案 here

它说我们必须清理 HTML 才能应用样式。

创建新管道:

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from "@angular/platform-browser";
@Pipe({
  name: 'safeHtml',
})
export class SafeHtmlPipe implements PipeTransform {

  constructor(private sanitizer:DomSanitizer){}

  transform(html) {
    return this.sanitizer.bypassSecurityTrustHtml(html);
  }
}

不要忘记在声明下将管道添加到模块中

@NgModule({
  declarations: [
    ...
    SafeHtmlPipe,
],

导入并使用它:

<span [innerHTML]="displayContent | safeHtml">

您必须使用 DomSanitizer[innerHTML] 绑定到 SafeHtml。

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

@Component({
  selector: 'my-app',
  template: `
   <div [style.width.px]="300">
     <div [innerHtml]="safeHTML"></div>
   </div>
  `,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  html = '<img src="https://via.placeholder.com/1000x1000" style="max-width: 100%" />';

  get safeHTML(): SafeHtml {
    return this.sanitizer.bypassSecurityTrustHtml(this.html);
  }

  constructor(private sanitizer: DomSanitizer) { }
}

Live demo