【问题标题】:Compile template based on injected config基于注入的配置编译模板
【发布时间】: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,但不确定它是否可以用于此...

标签: angular angular2-template


【解决方案1】:

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

然后在ngOnInit方法中:

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

【讨论】:

  • 也许我不够清楚 - 我需要以某种方式编译从 renderTemplate 获得的“网格”,因为我无法引用 pos1 或在你的情况下引用 @987654326 @ - error: Could not find variable anyRef 我会尽快提供 plnkr 或类似的东西 :)
【解决方案2】:

我认为这个问题可能会让您感兴趣,尤其是 alexpods 基于虚假组件的答案:

【讨论】:

  • 我已经偶然发现了这篇文章。但这似乎更像是一个“黑客”而不是一个干净的解决方案。 ://
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-28
  • 2012-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多