Waog Waog - 4 months ago 65
TypeScript Question

Angular2: Creating child components programmatically


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

selector: 'parent'
template: `
<h1>the children:</h1>
<!-- ??? three child views shall be inserted here ??? -->
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?


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


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

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: