加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – Angular2:以编程方式创建子组件

发布时间:2020-12-17 08:39:00 所属栏目:安全 来源:网络整理
导读:题 如何在父组件内部创建子组件,然后使用Angular2在视图中显示它们?如何确保注射剂正确注入子组件? 例 import {Component,View,bootstrap} from 'angular2/angular2';import {ChildComponent} from './ChildComponent';@Component({ selector: 'parent'})

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

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);

编辑

我在API docs preview中找到了DynamicComponentLoader。但是,在下面的示例中,我得到以下错误:没有动态组件指令在元素0

这通常不是我会采取的方法。相反,我将依赖于一个数组的数据绑定,将渲染更多的子组件,因为对象被添加到支持数组。基本上包含在ng-for中的子组件

我有一个例子在这里是相似的,因为它呈现一个动态的孩子列表。不是100%一样,但看起来似乎还是一样的概念:

http://www.syntaxsuccess.com/viewarticle/recursive-treeview-in-angular-2.0

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读