Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

innerHTML is not working for some tags like button or custom tags [duplicate]

Problem in interpolation when I assign some html tags(like button) or custom tag by angular interpolation then its not showing

In component.html file

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

In component.ts file

html = "<h1>Header</h1> <button>Button</button>"

Not working in angular https://stackblitz.com/edit/angular-j5gsb4?embed=1&file=app/app.component.ts

It's working in pure html/js https://plnkr.co/edit/3PWexJjKbOEe50egKjqJ?p=preview

like image 242
Akshay Garg Avatar asked Feb 20 '18 06:02

Akshay Garg


2 Answers

innerHTML is not a attribute exposed as a property of HTML Element.

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

So this will not work.

You can use @ViewChild to access DOM Element

app.component.html

<div #someVar></div>

app.component.ts

import {ElementRef} from '@angular/core';
@ViewChild('someVar') el:ElementRef;

constructor() {}

ngAfterViewInit() {
      this.el.nativeElement.innerHTML = "some html";
}
like image 61
void Avatar answered Oct 26 '22 21:10

void


By default Angular is sanitizing potential unsafe content. You can tell Angular to trust your content

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

export class AppComponent  {
  constructor(private sanitizer:DomSanitizer){
    this.html = sanitizer.bypassSecurityTrustHtml("<h1>Header</h1><button>Button</button>");
  }
  html;
}

StackBlitz example

See also https://stackoverflow.com/a/41089093/217408

like image 36
Günter Zöchbauer Avatar answered Oct 26 '22 23:10

Günter Zöchbauer