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
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";
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With