【发布时间】:2016-06-12 09:36:17
【问题描述】:
有没有办法根据注入的 Service 的值为组件动态创建模板?
Angular 2.0.0-beta.7
场景: 我得到一个包含嵌套组件的 json。我使用 DynamicComponentLoader 渲染这些组件(递归)。 这里我将自定义数据注入到组件中。
在这种情况下,我有一个类似于“布局组件”的东西,它获取一个包含布局配置的配置(1 行 - 三列)
代码看起来像这样:
{
"components": {
"name": "Layout",
"root": true,
"params": {
"cols": "3"
},
"children": [
{
"name": "Navigation",
"position": "pos1",
"children": [{...}]
},
{
"name": "Content",
"position": "pos2"
},
{
"name": "Sidebar",
"position": "pos3"
}
]
}
}
@Component({
selector: 'df-layout',
template: "<div>?</div>"
})
export class DfLayout {
constructor(@Inject('layoutConfig') layoutConfig) {
//layoutConfig ===> {cols: 3}
let templateString = renderTemplate(layoutConfig);
//TODO
//compile templateString and replace template so that template variables (#pos1, ...) can be used
/*
<div class="row">
<div class="col-4" #pos1></div>
<div class="col-4" #pos2></div>
<div class="col-4" #pos3></div>
</div>
*/
}
}
我知道如何根据配置创建 html。但我不知道如何“编译”它。只是将它传递给根 div 的 [innerHTML] 并不能完成这项工作,因为我需要本地模板变量来使用 DynamicComponentLoader.loadIntoLocation(...) 渲染子组件
有没有办法编译模板字符串并在当前模板中使用它?
【问题讨论】:
-
我有一个similar issue,但恐怕还没有解决方案。由于 ng1 中没有
$compile,因此我打算研究 Renderer,但不确定它是否可以用于此...