innerHtml not marking up correctly (Angular)

41 Views Asked by At

I'm using control.label to pull text from a database that is dynamically created depending on what part of the application a user is at. I need to make one word ("not") bold and underlined.

In my MSSQL database I wrapped the word not in <strong> tags to get it bold first, but Angular is rendering the text literally. It displays the tags instead of bolding it. I've tried DomSanitize and SafeHtml as well, and nothing seems to work.

In my database it's basically blah blah blah <strong tags>not blah blah blah under the label column (hence control.label when it is called in my HTML component). Then in my HTML I do this:

<div [innerHTML]="control.label"></div>

Hoping it would properly render the dynamic text, but it does not.

1

There are 1 best solutions below

0
Daniel Vágner On

You need to work with DomSanitizer. Bcs innerHTML property sanitizes the content by stripping out HTML tags to prevent XSS.

import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

export class YourComponent {
  safeHtml: SafeHtml;

  constructor(private sanitizer: DomSanitizer) {}


ngOnInit() {
  // this.control is just example
  this.safeHtml = this.sanitizer.bypassSecurityTrustHtml(this.control.label);
}

}

And now in HTML you can work with your response from DB like this.

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