druckreich
druckreich

Reputation: 33

Angular2 NgFor Within Components

I have a tree like structure and try to create a list from components and subcomponents in angular2.

var data = [
  {id:"1", 
   children: [
     {id:"2", 
      children: [
        {id: "3"},
        {id: "3"},
        {id: "3"},
        {id: "3"},
      ]},
      {id:"2", 
      children: [
        {id: "3"},
        {id: "3"},
        {id: "3"},
        {id: "3"},
      ]}
   ]}
]

I am trying to loop throught that structure and build an html list using different components depending on the depth of the loop iteration.

TypeScript

// ROOT
@Component({
    selector: 'root',
})

@View({
    templateUrl: '
    <childOne *ng-for="#data for list.children" [data]="data"></childOne>
    ',
    directives: [ChildOne, NgFor]
})

class Root{
    list:Array<Object>;
    constructor() {
       this.list = // request to backend
    }
}

// COMPONENT 1
@Component({
    selector: 'childOne',
    properties: ['data']
})

@View({
    templateUrl: '
    {{data.id}}
    <childTwo *ng-for="#childOneData for data.children" [data]="childOneData "></childTwo>
    ',
    directives: [ChildTwo, NgFor]
})

class ChildOne{
}

// COMPONENT 2
@Component({
    selector: 'childTwo',
    properties: ['data']
})

@View({
    templateUrl: '
    {{data.id}}
    <childThree *ng-for="#childTwoData for data.children" [data]="childTwoData"></childTwo>
    ',
    directives: [ChildThree, NgFor]
})

class ChildOne{
    constructor() {
    }
}

// COMPONENT 3
@Component({
    selector: 'childThree',
    properties: ['data']
})

@View({
    templateUrl: '{{data.id}}',
})

class ChildThree{
    constructor() {
    }
}

HTML

<head>
  <body>
    <root></root>
  </body>
</head>

Problem

I run into an error

Can't bind to 'ngForFor' since it isn't a know property of the 'template' element and there are no matching directives with a corresponding property

The Error refers to the *ng-for in the ChildTwo Component. When I remove the html tag everything works just fine.

Are there any limits when using *ng-for? Or some Pitfalls I did not see?

thx

Upvotes: 1

Views: 9596

Answers (1)

alexpods
alexpods

Reputation: 48477

You must use of instead of for in the ng-for directive:

<childTwo *ngFor="let childOneData of data.children" [data]="childOneData "></childTwo>

*ng-for changed to *ngFor

*#item changed to let item

Upvotes: 12

Related Questions