如何使放置在 innerHTML 属性中的 Popovers 起作用?

How to make Popovers placed inside a innerHTML attribute work?

我的 angular 组件中有一个带有 HTML 按钮代码的 printValue 变量,如下所示:

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(){}

}

问题是,一旦 printValue 变量被放置在内部 HTML 中,我如何使弹出窗口工作,如下所示:

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

这样做

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

直接在 html 文件中将启用弹出窗口。但是如何让它在 innerHTML 属性中工作呢?

在你的html

<div #container></div>

然后,在你的 ts 文件中,

 ....
export class MainDataComponent {

    @ViewChild('container') container: ElementRef;

    loadData(data) {// call this with your data
        this.container.nativeElement.innerHTML = data;
    }
}

像下面的代码一样做一些改变:

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(){}
}

如果它不起作用,请在您的组件中尝试 ViewChild & ElementRef:

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

在你的html中:

希望对您有所帮助。

默认情况下 angular 清理 html 代码以避免任何跨站点脚本攻击,但我们可以使用 DOMSanitizer 跳过它,它告诉 angular html 提供的内容是安全的。 寻找参考:

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

如果这个解决方案没有帮助,那么其他答案都很好,你可以试试。

希望对您有所帮助。