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 theNgFor
directive nor theCommonModule
was imported. Use Angular's built-in control flow@for
or make sure that either theNgFor
directive or theCommonModule
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
1. Use the New Angular Control Flow (Recommended)
Angular 17+ introduced a cleaner, more efficient template syntax:
<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:
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
:
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:
- Add
CommonModule
to your module's imports:
@NgModule({
imports: [CommonModule],
})
export class YourModule {}
- Remove
standalone: true
from components
Key Recommendations
- Prefer the new control flow (
@for
) for new Angular projects track
is mandatory in@for
for optimization- In standalone components, all dependencies must be explicitly imported
- Use minimal imports (
NgFor
instead ofCommonModule
) 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:
ng generate @angular/core:control-flow