我有一个printValue变量,在我的角度组件中有一个HTML按钮代码,如下所示:
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变量被放置在innerHTML中,我如何使popover工作,如下所示:
<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文件内部将使popover能够工作。但是如何使其在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内容是安全的。寻找参考:为Angular 2 RC6 组件提供DomSanitizer的正确方法
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>') ;
}
}
如果这个解决方案没有帮助,那么其他答案都很好,你可以试试。
希望能有所帮助。