angular – 基于注入配置编译模板

前端之家收集整理的这篇文章主要介绍了angular – 基于注入配置编译模板前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有办法根据注入的服务的值动态创建组件的模板?

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(…)渲染childComponents

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

解决方法

也许你可以为你可能必须在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');

猜你在找的Angularjs相关文章