Par*_*osh 45 typescript aem angular-cli angular2-compiler angular
我创建了一个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!';
}
Run Code Online (Sandbox Code Playgroud)
和app.component.html一样
<h1>
Good Morning, {{title}}
</h1>
Run Code Online (Sandbox Code Playgroud)
因此,当我使用ng build它生成它时会生成一些像这样的文件./dist/main.bundle.js,其中包含一些代码,如下所示 -
/* 586 */
/***/ function(module, exports) {
module.exports = "<h1>\n Good Morning, {{title}}\n</h1>\n"
/***/ },
/* 587 */
Run Code Online (Sandbox Code Playgroud)
这意味着,在构建时,编译器/ bundle-er正在读取html文件并将它们连接到生成的js文件中.
但在我的情况下,html也是动态的,内容驱动的是服务器端.可以说,我的模板文件不是html,而是app.component.jsp,并且完全驻留在一些不同的服务器或文件夹上.
此JSP文件有时会返回<h1>Good Morning, {{title}}</h1>
,有时还<h1>Good Afternoon, {{title}}</h1>取决于当前的服务器时间.
如何实现这一功能?
我的理解是,我需要定义某种加载器函数说: loadDynamicTemplate(template_url)
并且需要在Component decorator模板属性上使用该loader-function.在这种情况下,当生成main.bundle.JS时,它也将使用该函数.因此在运行时,angular将调用此函数并通过ajax加载HTML并使用它.
更新1
在这里,我发现SystemJS和Webpack之间存在一些差异.我还发现如果我们可以使用SystemJS,我们可以在运行时加载HTML文件.所以我相信这个问题可以通过SystemJS配置来解决.但是,为此,另一个问题开始发挥作用,尽管我认为这可能是一个单独的问题.所以我发布了一个新问题来解决这个问题.
可能如果这个问题得到解决,我会尝试使用SystemJS,然后在这里发布解决方案,如果有帮助的话.
Kar*_*538 36
你可以在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);
}
}
Run Code Online (Sandbox Code Playgroud)
Kar*_*538 18
要使用某些内容插入模板Good Morning, {{title}},您可以使用Suguru Inatomi的"ng-dynamic"组件.
首先你必须安装它:
npm install --save ng-dynamic
Run Code Online (Sandbox Code Playgroud)
然后导入你的NgModule:
@NgModule({
imports: [
...
DynamicComponentModule.forRoot({}),
...
],
...
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)
最后像这样使用它:
@Component({
selector: 'app-root',
template: '<div *dynamicComponent="template; context: bindings;"></div>'
})
export class AppComponent {
bindings: any = {title: "Chuck Norris"};
template: string = `
<h1>Good Morning, {{title}}</h1>
`;
constructor(http: Http) {
http.get("/path-to-your-jsp").map((html:string) => this.template = html); //<- You may set bindings in request headers...
}
}
Run Code Online (Sandbox Code Playgroud)
您可以通过定义SharedModule来使用模板中的组件.我添加了一个自定义的"我的按钮",其功能类似于此处的文档示例:https://github.com/laco0416/ng-dynamic
| 归档时间: |
|
| 查看次数: |
58467 次 |
| 最近记录: |