7

I have created angular application.in here, i want to inject some content using [innerHTML] property like below

export class AppComponent  {
  name = 'Angular';
  public bar = 'bars';
  foo = `<div>`+this.bar+`
  </div>
  <button type="button" onclick="alert('Hello world!')">Click Me!</button>
`;
}

I have used this in html file like below

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

But I just simply return only div element. button control is not getting rendered.

I have created a stackb sample for your reference. please provide any idea how to do it

sample - https://stackblitz.com/edit/angular-ena2xj?file=src/app/app.component.ts

Reference - Angular HTML binding

Kumaresan Sd
  • 1,399
  • 4
  • 16
  • 34

2 Answers2

15

you should use DomSanitizer

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  {
        constructor(private sanitized: DomSanitizer) {}

   name = 'Angular';
  public bar = 'bars';
  foo = this.sanitized.bypassSecurityTrustHtml( `<div>`+this.bar+`
  </div>
  <button type="button" onclick="alert('Hello world!')">Click Me!</button>
`);
}
Devraj s
  • 251
  • 2
  • 7
1

You can change it to @ViewChild,

Change your ts file like this,

export class AppComponent  {
  @ViewChild('someVar') el:ElementRef;
  name = 'Angular';
  public bar = 'bar';
  ngAfterViewInit() {
  this.el.nativeElement.innerHTML = `<div>`+this.bar+`
  </div><button type="button" onclick="alert('Hello world!')">Click Me!</button>`;
}
}

Working Stackblitz https://stackblitz.com/edit/angular-vnk9ft

Maniraj Murugan
  • 8,868
  • 20
  • 67
  • 116
  • @kumaresan_sd, Why don't you want to use ```ViewChild``` ?? – Maniraj Murugan May 24 '19 at 07:09
  • i don't want to take element reference because i have to inject this in multiple elements. – Kumaresan Sd May 24 '19 at 07:10
  • @kumaresan_sd, Okay this question https://stackoverflow.com/questions/48879407/innerhtml-is-not-working-for-some-tags-like-button-or-custom-tags propose both solutions, and another answer deals with first solution of it.. Hope you got better solution for your problem.. – Maniraj Murugan May 24 '19 at 07:12