Reputation: 121
I am trying use *ngFor to access array of objects. But it is throwing console errors.I have defined the array like this.
employees=[
{name:'a',age:'25'},
{name:'b',age:'35'}
];
In the html template file i am using *ngFor statements like this
<ul>
<li *ngFor="let employee of employees ; let i = index;">
{{name}}
</li>
</ul>
The browser throws console error like the below( the plukr is @ http://plnkr.co/edit/0cBHaDM1mHvMf38NtQ7X?p=preview)
Error: Uncaught (in promise): Error: Error in :0:0 caused by: Array[2] is not a constructor TypeError: Array[2] is not a constructor at new AppComponent (http://run.plnkr.co/0tyHWvPl7PnWfPkm/app/app.component.ts!transpiled:15:26) at new Wrapper_AppComponent
I am a bit new to Angular 2 and any help will be much appreciated.
Upvotes: 1
Views: 1239
Reputation: 41571
Mistakes
employees= new Array[2];
is not the way to instanciate an Array.names = new Array('qw','er');
invalid.Your code should be as
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `<h1>Hellotest {{name}}</h1>
<ul>
<li *ngFor="let name of names ; let j = index;">
{{name}}
</li>
</ul>
<ul>
<li *ngFor="let employee of employees ; let i = index;">
{{employee.name}}
</li>
</ul>
`
})
export class AppComponent {
name = 'Angular';
employees= new Array();
names = new Array();
constructor(){
this.employees=[
{name:'a',age:'25'},
{name:'b',age:'35'}
];
this.names=['qw','er'];
console.log(this.employees);
console.log(this.names);
}
}
If you don't want to use a constructor then you should be using the variable declarations as below
name = 'Angular';
employees:any[]= [
{name:'a',age:'25'},
{name:'b',age:'35'}
];
names:Array<string> = ['qw','er'];
Upvotes: 4
Reputation: 7466
Please change your layout to this:
<ul>
<li *ngFor="let employee of employees ; let i = index;">
{{employee.name}}
</li>
</ul>
The employee variable will be each element of your array, then you need to access the name property of this obeject
Upvotes: 3