【问题标题】:Convert stored string that contain html tag into html text formatting将包含 html 标记的存储字符串转换为 html 文本格式
【发布时间】:2017-12-18 09:41:10
【问题描述】:

我有一个将数据存储在 firebase 中的 Angular 项目。数据以字符串 (prdName: string;) 的形式存储在数据库中。我想问是否可以在<b>this is text</b>之类的字符串中放置一个html标签并将其存储,然后将它们绑定/查看为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}}

如果需要更多的 sn-ps,请告诉我。非常感谢您。

【问题讨论】:

    标签: html string angular typescript text-formatting


    【解决方案1】:

    你必须使用innerHtml来绑定html标签:

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

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

    【讨论】:

      【解决方案2】:

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

      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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-19
        • 1970-01-01
        • 1970-01-01
        • 2019-05-02
        • 1970-01-01
        • 2013-08-02
        • 2023-03-06
        相关资源
        最近更新 更多