Angular2如何将服务器上的HTML包含在一个<div>中?

8

我在服务器上获得了一系列HTML文件。例如:

我试图将这些文件包含到我的 angular2 v4 应用程序的一个<div>中。例如:

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

component.html

<div [innerHtml]="myHtmlTemplate"></div>

但是它没有起作用。我尝试了以下解决方案:
Angular4 将外部 HTML 页面加载到 div 中
在 Angular2 中动态加载 HTML 模板
但对于我来说都不起作用。请有人帮我解决这个问题好吗?

1
这不是你应该做的方式。请查看https://www.concretepage.com/angular-2/angular-4-ng-template-example#ngSwitch - msanford
谢谢@msanford,但我正在寻找一种解决方案,其中HTML模板位于与Angular应用程序不同的服务器上,并且仅通过链接导入。 HTML模板必须独立于Angular应用程序。 - Sergio Mendez
5个回答

12

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>

这是符合你要求的工作示例:

Stackblitz演示


我喜欢你的解决方案。不幸的是,它并不能适用于所有的 .html 文件。即使在 stackblitz 的演示中,也会返回控制台错误。如果你有其他的解决方案(除了 iframe),我想知道。谢谢。 - Sergio Mendez
@SergioMendez 这是因为网站没有发送HTML响应(可能是由于跨域请求)。如果您有返回HTML内容的网站列表,上述解决方案肯定会起作用。 - programoholic
1
非常感谢您。您真的帮助我找到了解决方案。 - Sergio Mendez

1

这应该可以解决:

首先,在您的组件.ts文件中,通过http请求获取html:

import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators'

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {

  constructor(private http: HttpClient) { }

  htmlString: string;

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

}

在您的组件.html中,只需使用单向数据绑定即可:
<div [innerHTML]="htmlString"></div> 

当然我试过了。然后 "responseType: 'text'" 返回以下错误:类型 '"text"' 不能赋值给类型 '"json"'.ts(2322) client.d.ts(639, 9):期望的类型来自于此处声明的属性 'responseType',类型为... - Sergio Mendez
你需要将 "responseType: 'text' as 'json'" 设置为 'json',以欺骗 TypeScript 编译器。 - Marco

0

在你的组件中,首先使用HTTP请求请求页面

this.http.get('http://docs.example.com/intro.html').map(response => response.text()).subscribe(html => Your_template = html);

使用safehtml管道与innerhtml一起使用,这样您的内联样式将被应用。 更多信息请参见GitHub页面(https://gist.github.com/klihelp/4dcac910124409fa7bd20f230818c8d1)

<div [innerHtml]="Your_template | safeHtml"></div>

0

你需要进行HTTP调用以将HTML以纯文本形式加载,并使用innerHtml加载到div中。

export class AppComponent implements OnInit {
name = 'Kissht';
KisshtHtml;
constructor(
 private http:HttpClient,
 private sanitizer:DomSanitizer){ }
ngOnInit(){
   this.http.get('https://kissht.com/', 
  {responseType:'text'}).subscribe(res=>{
    this.KisshtHtml = this.sanitizer.bypassSecurityTrustHtml(res);
  })
 }
}

有时候在 StackBlitz 中加载外部 HTML 时可能会遇到 CORS 问题。

https://stackblitz.com/edit/display-external-html-into-angular


0

你实际上想在你的Angular应用程序中显示一个页面,对吗?

为此,你可以添加一个iframe标签:

<iframe width="400" height="600" [src]="myHtmlTemplate"></iframe>

非常感谢,我正在避免使用<iframe>,因为我在Angular应用程序中有一些样式,我需要它们出现在服务器的template.html中。我需要的是一种方法去http://docs.example.com/page2.html,并将该文件转换为纯文本以使用[innerHtml],这样Angular样式就可以应用到此部分。 - Sergio Mendez

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接