user1965606
user1965606

Reputation: 41

Using ngFor in NativeScript + Angula2 application

I'm trying to show a list of labels with ngFor. BELTS is a simple data structure. each item in it have a subject.

I'm getting an error: JS: Error: Error in ./SilabusComponent class SilabusComponent - inline template:2:64 caused by: Cannot read property 'subject' of undefined.

seems that it doesn't know item. any idea?

following is the component decoretor:

@Component({
   selector: "kbm-silabus",
   template: `
      <StackLayout>
        <Label ngFor="let item of silabusList; let i=index"                    [text]="item.subject"></Label> 
    </StackLayout>
   `
})

export class SilabusComponent {
    private sub: any;
    silabusList: Array<Silabus>;

    ngOnInit() {
      this.page.actionBar.title = "KBM School";
      this.sub = this.route.params.subscribe(params => {
        this.id = params['id'];
        this.silabusList = [];
        this.silabusSubjects = [];

        BELTS[this.id].silabus.forEach((item, index) => {
            this.silabusList.push(new Silabus(item.subject, item.content));
            console.log(item.subject);
        })
      });
    }

    ngOnDestroy() {
      this.sub.unsubscribe();
    }

}

Upvotes: 4

Views: 6210

Answers (1)

Nick Iliev
Nick Iliev

Reputation: 9670

You have missed the asterisk sign in front of ngFor, which is very important as otherwise, you can only apply ngFor for templates with its full syntax. In NativeScript projects use the *ngFor syntax.

e.g.

<StackLayout *ngFor="let item of silabusList">
   <Label [text]="item.subject"></Label> 
</StackLayout>

Basically, this is how to achive the same output with the different syntax rules:

<!-- Examples (A) and (B) are the same -->

<!-- (A) *ngFor -->
<Label *ngFor="let hero of heroes" [text]="hero"></Label >

<!-- (B) ngFor with template -->
<template ngFor let-hero [ngForOf]="heroes">
  <Label [text]="hero"></Label >
</template>

Upvotes: 4

Related Questions