11

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

10
  • Better Use renderer2 service: alligator.io/angular/using-renderer2 Commented May 24, 2019 at 7:04
  • @Chellappan, Hi Bro, why not we use @viewChild?? Commented May 24, 2019 at 7:09
  • Better way to manipulte DOM in angular is using Render2 service. Commented May 24, 2019 at 7:11
  • @Chellappan, Okay bro, using Render2 service might be also a good solution i hope.. Commented May 24, 2019 at 7:15
  • hi @Chellappan, is there any guidelines available to use render 2 service Commented May 24, 2019 at 7:18

2 Answers 2

20

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>
`);
}
Sign up to request clarification or add additional context in comments.

4 Comments

HI @devraj, Thanks for your quick reply. it is working fine
I have one more doubt. is is possible to create another component and use here
that is not possible.
What about adding attribute binding to the foo? @Devrajs
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

3 Comments

@kumaresan_sd, Why don't you want to use ViewChild ??
i don't want to take element reference because i have to inject this in multiple elements.
@kumaresan_sd, Okay this question stackoverflow.com/questions/48879407/… propose both solutions, and another answer deals with first solution of it.. Hope you got better solution for your problem..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.