0

I'm pretty new to Angular & Typescript. Familiar with OOP & Javascript. And im bit confused as to how to do the following:

I want to create and insert a number of child component instances inside the parent component depending on a variable in the parent component. I also want to give each child component values that I pass it from the parent. Code below gives me: Uncaught Error: Can't resolve all parameters for ParentComponent: (?, ?). Which is confusing as hell to me since im passing the correct amount of parameters & correct types?

Parnet Component:

import { Component, OnInit } from '@angular/core';
import { ChildComponent } from './child/child.component';

@Component({
  selector: 'parent',
  template: `
      <ul>
      <li *ngFor='let child of collOfChildren'>
          <child></child>
      </li>
    </ul>
  `
})
export class ParentComponent implements OnInit {
  private collOfChildren: Array<ChildComponent> = [];

  numOfChildren = 3;
  childNames = ['Child 1', 'Child 2','Child 3'];

  constructor() { 
  }

  ngOnInit() {
    for(let i = 0; i < this.numOfChildren; i++) {
      this.collOfChildren.push(new ChildComponent(this.childNames[i],5));
    }
  }

}

Child Component:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
  private name:String;
  private age:number;

  constructor(name:String, age:number) { 
    this.name = name;
    this.age = age;
  }

  ngOnInit() {
  }

}
Snar3
  • 68
  • 1
  • 11
  • 4
    Possible duplicate of [Angular 2 DI Error - EXCEPTION: Can't resolve all parameters](https://stackoverflow.com/questions/37997824/angular-2-di-error-exception-cant-resolve-all-parameters) – Harsha Jayamanna Nov 05 '17 at 04:56

1 Answers1

0

The Angular tutorial has correct practice,you do not need to init child components array ,you just need to pass the child data to child component as below:

<child *ngFor="let childName of childNames" [name]="childName">

And you need add Input decorator to name of childComponnet as below:

@Input() name: string;
Hayden
  • 449
  • 4
  • 13