angular - 在angular2中动态加载HTML模板

标签 angular typescript aem angular-cli angular2-compiler

我已经使用 angular-cli 创建了一个项目其中包含如下 AppComponent:

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';
}

app.component.html作为

<h1>
  Good Morning, {{title}}
</h1>

所以当我用 ng build 构建它时它生成一些像这样的文件 ./dist/main.bundle.js 其中包含一些代码如下 -

/* 586 */
/***/ function(module, exports) {

module.exports = "<h1>\n  Good Morning, {{title}}\n</h1>\n"

/***/ },
/* 587 */

这意味着,在构建时,编译器/bundle-er 正在读取 html 文件并将它们连接到生成的 js 文件中。

但在我的例子中,html 也是动态 并且由服务器端的内容驱动。比方说,我的模板文件不是 html,而是 app.component.jsp 并且完全驻留在某个不同的服务器或文件夹上。

此外,JSP 文件有时会返回 <h1>Good Morning, {{title}}</h1> 有时 <h1>Good Afternoon, {{title}}</h1>取决于当前服务器时间。

如何实现这个功能?

我的理解是,我需要定义某种加载程序函数,例如:loadDynamicTemplate(template_url)

并且需要在组件装饰器模板属性上使用该加载器函数。在这种情况下,当生成 main.bundle.JS 时,它也会使用该函数。因此在运行时 Angular 将调用此函数并通过 ajax 加载 HTML 并使用它。

更新 1

Here我发现 SystemJS 和 Webpack 之间存在一些差异。我还发现如果可以使用 SystemJS,我们可以在运行时加载 HTML 文件。所以我相信这个问题可以通过 SystemJS 配置来解决。但是为此,另一个问题开始发挥作用,尽管我认为这可能是一个单独的问题。所以我发了一个新问题来整理一下here .

如果这个问题得到解决,我可能会尝试使用 SystemJS,然后在此处发布解决方案(如果有帮助的话)。

最佳答案

您可以在 my-template 组件中使用 [innerHtml] 类似这样的东西(我没有测试):

@Component({
    selector: 'my-template',
    template: `
<div [innerHtml]="myTemplate">
</div>
`})
export public class MyTemplate {
    private myTemplate: any = "";
    @Input() url: string;
    constructor(http: Http) {
        http.get("/path-to-your-jsp").map((html:any) => this.myTemplate = html);
    }
}

关于angular - 在angular2中动态加载HTML模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40786490/

相关文章:

reactjs - 使用 ref 作为 Material UI InputLabel

AEM 6.1 Sightly 基本表单提交并重定向到同一页面

aem - 如何避免在 CQ 中页面的所有链接中硬编码 .html 扩展名?

javascript - Angular 2 和 SQLite 连接

angular - NGRX/RXJS : How to recursively map observable streams into a single flat stream

angularjs - ionic 调用服务

javascript - typescript :无法访问继承类构造函数中的成员值

java - Adobe Experience Manager 中的 netdiagnostics Java 代理启动错误

angular - 添加 "angularCompileRows: true"后 Ag-grid 单元不编译事件

angular - 如何以表格形式发送mat-chip-list