Search code examples
angulartypescriptangular2-ngfor

*ngFor fails in angular 2


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.


Solution

  • Mistakes

    1. You used the markup in index.html.
    2. employees= new Array[2]; is not the way to instanciate an Array.
    3. names = new Array('qw','er'); invalid.
    4. Did not use a constructor to assign values.(Bad practice)

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

    Updated plunker

    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'];
    

    No Constructor plunker