Marco Jr
Marco Jr

Reputation: 6806

Angular - InnerHtml with styles

I've this...

const htmlVar = "<html>
<div style="display:flex">
<div>
  <h1>Hello World</h1>
</div>
</div>
";

and on my html I've this..

 <div [innerHtml]="htmlVar"></div>

It's render everything, but the style :(

I attempted the solution of this link: style not working for innerhtml in Angular 2 Typescript

but it's not working. Maybe because it's too old.

Any clue ?

Upvotes: 0

Views: 669

Answers (1)

Andriy
Andriy

Reputation: 15472

As @R.Richards mentioned, use DomSanitizer:

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

constructor(protected _sanitizer: DomSanitizer) {
  this.htmlVar = this._sanitizer.bypassSecurityTrustHtml(`
    <html>
      <head></head>
      <body>
        <div style="display:flex; color: red;">
          <div>
            <h1>Hello World</h1>
          </div>
        </div>
      </body>
    </html>`);
}

I created a stackblitz to illustrate

Also, as @liam already mentioned you should not have <html>, <header>, or <body> tags as DIV's children

Upvotes: 4

Related Questions