如何将 HTML 字符串从 component.ts 传输到 component.html

2024-05-20

我想问一下如何将HTML格式的字符串从.component.ts文件到.component.html file.

在我的应用程序中有一个布局文件夹。这layout.component.ts文件有代码:

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

@Component({
  selector: 'app-layout',
  templateUrl: './layout.component.html',
  styleUrls: ['./layout.component.css']
})

export class LayoutComponent implements OnInit {
  htmlText: string;

  constructor() {
   }

  ngOnInit() {
    this.htmlText = '<b>title</b> Title Hier <FONT color="blue"><i>some texts hier.</i></FONT>';
  }
}

文本及其 HTML 格式均已定义。因此,我想在浏览器中显示带有自己的 HTML 定义的文本。

The layout.component.html文件看起来像:

<h2>{{ htmlText }}</h2>

编译后浏览器显示 htmlText 字符串的完整文本,但 HTML 格式被忽略。

我做错了什么?感谢您的任何提示+帮助。


使用以下代码创建管道:

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';


@Pipe({ name: 'keepHtml', pure: false })
export class SafePipe implements PipeTransform {
constructor(private _sanitizer: DomSanitizer) {
}

public transform(value: string, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
switch (type) {
    case 'html':
        return this._sanitizer.bypassSecurityTrustHtml(value);
    case 'style':
        return this._sanitizer.bypassSecurityTrustStyle(value);
    case 'script':
        return this._sanitizer.bypassSecurityTrustScript(value);
    case 'url':
        return this._sanitizer.bypassSecurityTrustUrl(value);
    case 'resourceUrl':
        return this._sanitizer.bypassSecurityTrustResourceUrl(value);
    default:
        throw new Error(`Unable to bypass security for invalid type: ${type}`);
}
}
}

并在 html 文件中使用以下代码行:

<div [innerHtml]="htmlBody | keepHtml: 'html'"></div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 HTML 字符串从 component.ts 传输到 component.html 的相关文章

随机推荐