Wira Xie
Wira Xie

Reputation: 839

Convert stored string that contain html tag into html text formatting

I have an Angular project that stores data inside firebase. The data is stored as string (prdName: string;) inside the database. I want to ask if is it possible if i put a html tag inside the string like <b>this is text</b> and store it and then bind/view them as html text format? (the text become bold)

firebase

//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}}

Please let me know if more snippets are needed. Thank you very much in advance.

Upvotes: 2

Views: 1197

Answers (2)

kriss
kriss

Reputation: 1015

I used such pipe in my project to make it work right

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);
  }
}

then in the place where you want to have your html you simply do

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

pipe is needed to make this html content trusted, more information about this:

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

Upvotes: 1

br.julien
br.julien

Reputation: 3460

You have to use innerHtml to bind html tags :

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

Check this : https://angular.io/guide/template-syntax#!#property-binding-or-interpolation-

Upvotes: 1

Related Questions