How to make Popovers placed inside a innerHTML attribute work?

橙三吉。 提交于 2019-12-10 14:39:23

问题


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?


回答1:


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;
    }
}



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/51373442/how-to-make-popovers-placed-inside-a-innerhtml-attribute-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!