我的服务器中有一系列的 html。例如:
我试图将这些文件包含到 <div>
中在我的 angular2 v4 应用程序中。例如:
组件.ts
public changePage(name: string) {
switch (name) {
case 'intro': this.myHtmlTemplate = 'http://docs.example.com/intro.html'; break;
case 'page1': this.myHtmlTemplate = 'http://docs.example.com/page1.html'; break;
case 'page2': this.myHtmlTemplate = 'http://docs.example.com/page2.html'; break;
}
}
组件.html
<div [innerHtml]="myHtmlTemplate"></div>
但它不起作用。我尝试了以下解决方案:
Angular4 Load external html page in a div
Dynamically load HTML template in angular2
但这对我不起作用。有人可以帮我解决这个问题吗?
最佳答案
Angular 安全阻止 HTML 和其他脚本的动态呈现。您需要使用 DOM Sanitizer 绕过它们。
在这里阅读更多:Angular Security
在您的代码中做以下更改:
// in your component.ts file
//import this
import { DomSanitizer } from '@angular/platform-browser';
// in constructor create object
constructor(
...
private sanitizer: DomSanitizer
...
){
}
someMethod(){
const headers = new HttpHeaders({
'Content-Type': 'text/plain',
});
const request = this.http.get<string>('https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Your_first_HTML_form', {
headers: headers,
responseType: 'text'
}).subscribe(res => this.htmlString = res);
this.htmlData = this.sanitizer.bypassSecurityTrustHtml(this.htmlString); // this line bypasses angular security
}
在 HTML 文件中;
<!-- In Your html file-->
<div [innerHtml]="htmlData">
</div>
这是您的要求的工作示例:
关于html - Angular2 将来自服务器的 html 包含到一个 div 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56550946/