2016-02-29 121 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é」的本地支持...... –