Angular2:创建子组件编程 [英] Angular2: Creating child components programmatically

查看:225
本文介绍了Angular2:创建子组件编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建子组件的父组件内,使用的 Angular2 的事后在视图中显示它们?如何确保注射剂被正确注射到子组件?

How to create child components inside a parent component and display them in the view afterwards using Angular2? How to make sure the injectables are injected correctly into the child components?

import {Component, View, bootstrap} from 'angular2/angular2';
import {ChildComponent} from './ChildComponent';

@Component({
    selector: 'parent'
})
@View({
  template: `
    <div>
      <h1>the children:</h1>
      <!-- ??? three child views shall be inserted here ??? -->
    </div>`,
  directives: [ChildComponent]
})
class ParentComponent {

        children: ChildComponent[];

        constructor() {
            // when creating the children, their constructors
            // shall still be called with the injectables.
            // E.g. constructor(childName:string, additionalInjectable:SomeInjectable)
            children.push(new ChildComponent("Child A"));
            children.push(new ChildComponent("Child B"));
            children.push(new ChildComponent("Child C"));
            // How to create the components correctly?
        }
}
bootstrap(ParentComponent);

修改

我找到了 DynamicComponentLoader 中的 API文档preVIEW 。但我得到以下错误,当下面的例子:有元素0无活力的组成部分指令

Edit

I found the DynamicComponentLoader in the API docs preview. But I get the following error when following the example: There is no dynamic component directive at element 0

推荐答案

这通常不是我会采取的做法。相反,我将依靠对数据绑定的数组将呈现出更多的子组件为对象添加到支持数组。从本质上讲子组件包裹在一个NG换

This is generally not the approach I would take. Instead I would rely on databinding against an array that will render out more child components as objects are added to the backing array. Essentially child components wrapped in an ng-for

我这里有一个例子是,它使儿童的动态列表相似。不是100%相同,但好像这个概念仍然是相同的:

I have an example here that is similar in that it renders a dynamic list of children. Not 100% the same, but seems like the concept is still the same:

<一个href=\"http://www.syntaxsuccess.com/viewarticle/recursive-treeview-in-angular-2.0\">http://www.syntaxsuccess.com/viewarticle/recursive-treeview-in-angular-2.0

这篇关于Angular2:创建子组件编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆