Rob None
Rob None

Reputation: 581

Show html color from a string

I have a string, in a variable "prod.de.description", that is a description of an object, like that:

"<p><strong>Test</strong></p><p><strong><span style="background-color: #ed7e32;">Test2</span></strong></p>"

When I use innerhtml, it's show only the strong but not the background color. Here is the html code and the result:

 <div class="col-10" style="padding-left:0; font-size:0.9rem">
    <div class="row">
      <div class="col-3 text-right">
        <label class="modal-tag">DESCRIPTION</label>
      </div>
      <div class="col-9">
        <p [innerHTML]="prod.de.description"></p>
      </div>
    </div>

That's what I get since now:

The result of my code

Why I don't get the background color under Test2 but only the strong? I'm newbie of HTML. Thanks a lot!

Upvotes: 0

Views: 222

Answers (2)

vipul patel
vipul patel

Reputation: 736

you are using innerHTML directive of framework and it sanitises the content before putting into your dom. It will remove styles tag and script things as security issue. Outsiders can attack with their on content. To prevent that, framework does this thing.

However, framework also gives way to escape this when you know that you are putting content from trusted sources.

Follow this link:

https://stackblitz.com/edit/angular-8-app-example-mzdwkd

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

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

export class AppComponent  {

  description = '<p><strong>Test</strong></p><p><span style="background-color: #ed7e32;">Test2</span></p>';

  constructor(private sanitizer: DomSanitizer){}

   transformYourHtml(htmlTextWithStyle) {
       return this.sanitizer.bypassSecurityTrustHtml(htmlTextWithStyle);
   }
  }

HTML:

<p [innerHTML]="transformYourHtml(description)"></p>

Upvotes: 1

Jax-p
Jax-p

Reputation: 8583

You are using same quotation marks (") inside and outside of string. That might cause the problem. Use different ones. Maybe something like this:

"<p><strong>Test</strong></p><p><strong><span style='background-color: #ed7e32;'>Test2</span></strong></p>"

Upvotes: 2

Related Questions