Skip to content

Resolving Angular's *ngFor Directive Import Error

Problem Statement

When using Angular's *ngFor directive in your template, you might encounter this error:

The *ngFor directive was used in the template, but neither the NgFor directive nor the CommonModule was imported. Use Angular's built-in control flow @for or make sure that either the NgFor directive or the CommonModule is included in the @Component.imports array of this component.

This error occurs because:

  • You're using Angular 17+ with standalone components (default in new Angular projects)
  • The required Angular common directives aren't imported to your component
  • Your template uses the legacy *ngFor syntax without necessary imports

Three Solutions

Angular 17+ introduced a cleaner, more efficient template syntax:

html
<ul>
  @for (c of contacts; track c.id) {
    <li>{{c.id}} - {{c.name}}</li>
  }
</ul>

Benefits:

  • No imports required
  • Better performance with mandatory track
  • Future-proof syntax
  • Explicit block syntax (@empty supported)

2. Import NgFor Directive

If you prefer *ngFor, import the directive directly:

typescript
import { Component } from '@angular/core';
import { NgFor } from '@angular/common'; // Add this import

@Component({
  standalone: true,
  imports: [NgFor], // Register NgFor here
  templateUrl: './contacts.component.html',
})
export class ContactsComponent {
  contacts = [
    { id: 1, name: 'Alex' },
    { id: 2, name: 'Taylor' }
  ];
}

3. Import CommonModule

For components using multiple common directives, import the entire CommonModule:

typescript
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common'; // Import CommonModule

@Component({
  standalone: true,
  imports: [CommonModule], // Add CommonModule here
  templateUrl: './app.component.html',
})
export class AppComponent {
  contacts = [
    { id: 1, name: 'Alex' },
    { id: 2, name: 'Taylor' }
  ];
}

WARNING

If you're using NgModule instead of standalone components:

  1. Add CommonModule to your module's imports:
typescript
@NgModule({
  imports: [CommonModule], 
})
export class YourModule {}
  1. Remove standalone: true from components

Key Recommendations

  1. Prefer the new control flow (@for) for new Angular projects
  2. track is mandatory in @for for optimization
  3. In standalone components, all dependencies must be explicitly imported
  4. Use minimal imports (NgFor instead of CommonModule) when possible for smaller bundles

Error Origin Explanation

Angular 17+ defaults to standalone components that don't automatically import CommonModule. Since both *ngFor and *ngIf directives are part of this module, you must either:

  • Import the directives (NgFor)
  • Import the entire CommonModule
  • Use the modern syntax that doesn't require imports

TIP

Migrate existing *ngFor loops to @for with Angular's automatic migration:

bash
ng generate @angular/core:control-flow