Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 *ngFor not working

Following is my Component:

import { Component } from 'angular2/core';

@Component({
  selector: 'test',
  template: 
     `
      <ul >
        <li *ngFor="let t of test">
         <span >{{t}}</span>
        </li>
      </ul>
     `
})

export class TestComponent implements OnInit{
  test: string[];
  constructor(){
    this.test = ["Saab", "Volvo", "BMW"];
  }
}

I am getting the following error when I try to load the component:

  EXCEPTION: Template parse errors:
    Can't bind to 'ngFor' since it isn't a known native property ("<ul >
        <li [ERROR ->]*ngFor="let t of test">
            <span >{{t}}</span>
        </li>
    "): 

Also, I am not sure whether I should use '@angular/core' or 'angular2/core' while importing Component.

like image 702
UnderWood Avatar asked Jun 14 '16 21:06

UnderWood


People also ask

Can we use two ngFor?

We can nest muliple NgFor directives together. We can get the index of the item we are looping over by assigning index to a variable in the NgFor expression.

Can't bind to ngFor since it isn't a known property of span?

ngFor is not a known property would mean for whatever reason, ngFor cannot be recognized in the application. However, the real problem was that ngFor was recognised but the syntax of ngFor was wrong. Anyway, let's hope Angular team improves their logging in future updates.

What is * ngFor?

Introduction. *ngFor is a predefined directive in Angular. It accepts an array to iterate data over atemplate to replicate the template with different data. It's the same as the forEach() method in JavaScript, which also iterates over an array.

Can we have ngIf and ngFor together?

Use ngFor and ngIf on same element It's very common scenario where we want to repeat a block of HTML using ngFor only when a particular condition is true. i.e., if ngIf is true.So in this case to use *ngIf and *ngFor on same element, place the *ngIf on a parent element that wraps the *ngFor element.


1 Answers

The problem might occur because you havent imported the common module to your current module your'e using.

try import

import { CommonModule } from "@angular/common";

into your current module and see if the issue fixed.

the common module add all the built in directives from angular 2.

see commonModule documentation by angular.io

hope that helps :)

like image 80
razma Avatar answered Sep 30 '22 23:09

razma