2016-02-29 120 views
4

有没有一种方法可以根据注入服务的值动态创建组件模板?基于注入配置编译模板

角2.0.0 beta.7

场景: 我得到一个包含嵌套组件的JSON。我使用DynamicComponentLoader呈现这些组件(递归)。 在这里,我将自定义数据注入组件。

在这种情况下我有像它获取包含配置用于布局的配置(1行 - 3列)一“布局组分”

代码看起来类似的东西:

{ 
     "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。但我不知道如何“编译”它。只是将它传递到[innerHTML]的根div不做这项工作,因为我需要使用本地模板变量呈现childComponents使用DynamicComponentLoader.loadIntoLocation(...)

有没有办法编译模板字符串并在当前模板中使用它?

+0

我有一个[类似的问题(http://stackoverflow.com/q/35685342/1876949),但没有办法解决呢,我afrai d。由于没有像ng1那样的'$ compile',我打算查看[Renderer](https://github.com/angular/angular/blob/2.0.0-beta.7/modules/angular2/src/platform /dom/dom_renderer.ts),但不知道它是否可用于此... – Sasxa

回答

0

也许你可以为每个孩子创建一个@Component,你可能需要在DOM中插入。例如:NavigationComponent,ContentComponent等..

然后在ngOnInit方法:

Type type; 
if(children.name === 'Navigation') { 
type = NavigationComponent; 
}if(children.name === 'Content') { 
type = ContentComponent; 
} 
dynamicComponentLoader.loadIntoLocation(type,this.elementRef,'anyRef'); 
+0

也许我不太清楚 - 我需要以某种方式编译我从'renderTemplate'得到的“网格”,因为我不是能够引用'pos1'或在你的情况下'anyRef' - '错误:无法找到变量anyRef'我会提供一个plnkr或类似的东西:) –

0

我觉得这个问题可能基于虚假成分上你感兴趣,特别是alexpods的回答是:

+0

我已经偶然发现了这篇文章。但它似乎更像是一种“黑客”而不是一个干净的解决方案。 :/ –

+0

是的同意!由于没有对“compilé”的本地支持...... –