简体   繁体   中英

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.

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 :)

I ran into the same problem, after a lot of searching and testing, I just found out that I forget declare my component in the 'declarations' in the module.

 import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterModule } from '@angular/router'; import { SearchComponent } from './search.component'; @NgModule({ imports: [ CommonModule, RouterModule.forChild([ { path: '', component: SearchComponent }, ]) ], exports:[ ], declarations: [ SearchComponent ], }) export class SearchModule { }

Your template should be:

<ul>
    <li *ngFor="#t of test">
        <span >{{t}}</span>
    </li>
</ul>

Or this way in newer versions:

<ul>
    <li *ngFor="let t of test">
        <span>{{t}}</span>
    </li>
</ul>

I experienced a similar behavior. The problem was that I was including the minimized version of Angular 2 in my HTML.

If it is so, try to include the unminimized file of Angular

Using Let resolved the issue for me

 <ul> <li *ngFor = "let test of testArray">{{test}}</li> </ul>

By me the problem was that I was using Webpack with a HTML loader that was minimizing the HTML before Angular got to compile it thereby removing the * from the ngFor .

{
    test: /\.html$/,
    use: [ {
        loader: 'html-loader',
        options: {
        //minimize: true, // Make sure that you are not minimizing when using Angular
        removeComments: false,
        collapseWhitespace: false
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM