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

Wao*_*aog 37 javascript typescript angular

如何在父组件内创建子组件,然后使用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);
Run Code Online (Sandbox Code Playgroud)

编辑

DynamicComponentLoaderAPI文档预览中找到了.但是在遵循示例时出现以下错误:元素0处没有动态组件指令

TGH*_*TGH 18

这通常不是我采取的方法.相反,我依赖于对数组的数据绑定,当数组被添加到后备数组时,该数组将呈现更多的子组件.基本上包含在ng-for中的子组件

我在这里有一个类似的例子,它呈现一个动态的子列表.不是100%相同,但似乎概念仍然是相同的:

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

  • 添加围绕为什么`这通常不是办法的一些信息,我会take`可帮助人 (4认同)

Ans*_*hul 11

警告:RC.4中已弃用DynamicComponentLoader

在角2.0 loadIntoLocation的方法DynamicComponentLoader达到这个目的建立亲子关系的.通过使用此方法,您可以动态创建两个组件之间的关系.

以下是示例代码,其中纸张是我的父级,公告是我的子组件.

paper.component.ts

import {Component,DynamicComponentLoader,ElementRef,Inject,OnInit} from 'angular2/core';
import { BulletinComponent } from './bulletin.component';

@Component({
    selector: 'paper',
    templateUrl: 'app/views/paper.html'

    }
})
export class PaperComponent {
    constructor(private dynamicComponentLoader:DynamicComponentLoader, private elementRef: ElementRef) {

    }

    ngOnInit(){
        this.dynamicComponentLoader.loadIntoLocation(BulletinComponent, this.elementRef,'child');

    }
}
Run Code Online (Sandbox Code Playgroud)

bulletin.component.ts

import {Component} from 'angular2/core';

@Component({
    selector: 'bulletin',
    template: '<div>Hi!</div>'
    }
})
export class BulletinComponent {}
Run Code Online (Sandbox Code Playgroud)

paper.html

<div>
    <div #child></div>
</div>
Run Code Online (Sandbox Code Playgroud)

在这个答案中提到了你需要注意的几件事


Shi*_*pta 6

您应该使用ComponentFactoryResolver和ViewElementRef在运行时添加组件.让我们看看下面的代码.

let factory = this.componentFactoryResolver.resolveComponentFactory(SpreadSheetComponent);
let res = this.viewContainerRef.createComponent(factory);
Run Code Online (Sandbox Code Playgroud)

将上面的代码放在ngOnInit函数中,并用组件名称替换"SpreadSheetComponent".

希望这会奏效.