5

I have this printValue variable with a HTML button code inside my angular component like so:

export class HomeComponent implements OnInit {

  printValue = '<button type="button" data-toggle="popover" title="Popover Header" data-content="Some content inside the popover">Popover</button>';

  constructor(){}
  OnInit(){}

}

The question is, how do i make the popover work once the printValue variable has been placed inside the innerHTML as seen below:

<p [innerHTML]="printValue"></p>

Doing this

<body>
<button type="button" data-toggle="popover" title="Popover Header" data-content="Some content inside the popover">Popover</button>
</body>

inside an html file directly will enable popovers to work. But how to make it to work inside a innerHTML attribute?

Shubham Verma
  • 8,783
  • 6
  • 58
  • 79
dalemncy
  • 609
  • 8
  • 26

3 Answers3

4

In your html

<div #container></div>

Then, in your ts file,

 ....
export class MainDataComponent {

    @ViewChild('container') container: ElementRef;

    loadData(data) {// call this with your data
        this.container.nativeElement.innerHTML = data;
    }
}
Malindu Sandaruwan
  • 1,477
  • 2
  • 13
  • 27
1

Do some change like in below code:

export class HomeComponent implements OnInit {
  printValue : string = '<button type="button" data-toggle="popover" title="Popover Header" data-content="Some content inside the popover">Popover</button>';
  constructor(){}
  OnInit(){}
}

If it doesn't work then try ViewChild & ElementRef in your component:

import { ViewChild, ElementRef , Component  } from '@angular/core';

@Component({
    .......
})
export class YourComponent {


    @ViewChild('htmlId') htmlId: ElementRef;

      printValue : string = '<button type="button" data-toggle="popover" title="Popover Header" data-content="Some content inside the popover">Popover</button>';


    addHTML(data) {
        this.htmlId.nativeElement.innerHTML = printValue;
    }
}

In your html:

Hope it will help you.

Shubham Verma
  • 8,783
  • 6
  • 58
  • 79
1

By default angular sanitises html code to avoid any cross site scripting attacks, but we can skip that by using DOMSanitizer which tells angular that html content provided is safe. Look for reference :Correct way Provide DomSanitizer to Component with Angular 2 RC6

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

@Component({
  selector: 'my-app',
  template: `
     <p [innerHtml]="paragraphHtml"></p>
  `,
})
export class App {
  constructor(private domsanitizer: DomSanitizer) {
    this.paragraphHtml = domsanitizer.bypassSecurityTrustHtml('<p>My other child paragraph</p><script>any script function you want to execute</script><div>Thank you</div>') ;
  }
}

if this solution is no help, then other answers are all good, you can try.

Hope it helps.

Abhishek Kumar
  • 2,501
  • 10
  • 25