加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 资源网站 > 资源 > 正文

在角度2中动态加载HTML模板

发布时间:2020-12-14 21:42:29 所属栏目:资源 来源:网络整理
导读:我已经使用了包含AppComponent的angular-cli创建了一个项目,如下所示: import { Component } from '@angular/core';@Component({ selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css']})export class AppCompone
我已经使用了包含AppComponent的angular-cli创建了一个项目,如下所示:
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 as

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

所以当我使用ng构建它生成一些这样的文件./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>早安,{{title}}< / h1>
并且有时< h1> Good Afternoon,{{title}}< / h1>取决于当前的服务器时间。

如何实现这个功能?

我所了解的是,我需要定义一些加载器函数说:loadDynamicTemplate(template_url)

并且需要在Component decorator模板属性上使用该loader功能。在这种情况下,当生成main.bundle.JS时,它也会使用该函数。所以在运行时角度会调用这个函数,并通过ajax加载HTML并使用它。

更新1

Here我发现SystemJS和Webpack有一些区别。我也发现如果我们可以使用SystemJS,我们可以在运行时加载HTML文件。所以我相信这个问题可以通过SystemJS配置来解决。但是,另一个问题是发挥作用,虽然我认为这可能是一个单独的问题。所以我发布了一个新的问题来排除here。

可能如果这个问题得到解决,我会尝试使用SystemJS,然后在这里解决这个问题,如果它有帮助。

解决方法

你可以在我的模板组件中使用[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);
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读