Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
103
rated 0 times [  106] [ 3]  / answers: 1 / hits: 36829  / 9 Years ago, sun, june 14, 2015, 12:00:00

Question



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?



Example



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


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


More From » angular

 Answers
28

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:



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


[#66213] Thursday, June 11, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaycoborionc

Total Points: 220
Total Questions: 106
Total Answers: 120

Location: Kenya
Member since Mon, Jun 14, 2021
3 Years ago
;