将包含 html 标记的存储字符串转换为 html 文本格式

Convert stored string that contain html tag into html text formatting

我有一个 Angular 项目将数据存储在 firebase 中。数据在数据库中存储为字符串 (prdName: string;)。我想问一下是否可以将 html 标记放入 <b>this is text</b> 之类的字符串中并存储它,然后将它们 bind/view 作为 html 文本格式? (文字变为粗体)

//service.ts
getData() {
  this.List = this.firebase.list('Product');
  return this.List;
}

insertProduct(Product: Product) {
  this.productList.push({
    prdName: Product.prdName,
    prdCategory: Product.prdCategory,
    prdSup: Product.prdSup,
    prdImage: Product.prdImage,
    prdDescription: Product.prdDescription
  });
}

//component.ts
ngOnInit() {
  var x = this.ListService.getData();
  x.snapshotChanges().subscribe(item => {
    this.List = [];
    item.forEach(element => {
      var y = element.payload.toJSON();
      y["$prdKey"] = element.key;
      this.List.push(y as List);
    });
  });
}
<!--component.html-->
<label>Product Name: </label> {{ListService.selectedProduct.prdName}}

如果需要更多片段,请告诉我。非常感谢您。

您必须使用 innerHtml 绑定 html 标签:

<div [innerHTML]="ListService.selectedProduct.prdName"></div>

检查这个:https://angular.io/guide/template-syntax#!#property-binding-or-interpolation-

我在我的项目中使用了这样的管道使其正常工作

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

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

  transform(value) {
    return this.sanitized.bypassSecurityTrustHtml(value);
  }
}

然后在你想要 html 的地方你只需做

<div [innerHTML]="someHtmlContent | safeHtml"></div> 

需要管道才能使此 html 内容可信,有关此内容的更多信息:

https://angular.io/guide/security#bypass-security-apis