Resolving Angular's *ngFor Directive Import Error
Problem Statement
When using Angular's *ngFor directive in your template, you might encounter this error:
The
*ngFordirective was used in the template, but neither theNgFordirective nor theCommonModulewas imported. Use Angular's built-in control flow@foror make sure that either theNgFordirective or theCommonModuleis included in the@Component.importsarray 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
*ngForsyntax 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 (
@emptysupported)
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
CommonModuleto your module's imports:
@NgModule({
imports: [CommonModule],
})
export class YourModule {}- Remove
standalone: truefrom components
Key Recommendations
- Prefer the new control flow (
@for) for new Angular projects trackis mandatory in@forfor optimization- In standalone components, all dependencies must be explicitly imported
- Use minimal imports (
NgForinstead 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