If you’re working with Angular and have encountered the error "Property 'ngForOf' is not provided by any applicable directive on an embedded template," you’re not alone.
This error is a common stumbling block, especially for developers just starting with Angular’s *ngFor directive, which is used to iterate over a collection within templates.
The fix can be simple, but understanding the root cause helps avoid it in the future. In this guide, we’ll walk through why this happens, provide a variety of solutions, and include practical code examples along the way.
Why the Error Happens
This error usually indicates that Angular cannot find the directive to interpret the *ngFor syntax in your template. This often happens when the required CommonModule is missing, especially when using Angular modules like @NgModule.
CommonModule includes several basic Angular directives, including *ngFor and *ngIf. Without it, Angular has no knowledge of these directives and will throw an error.
Solution 1: Import CommonModule in Your Module
One of the most common reasons for this error is that the CommonModule is not imported in your module file. In Angular, each module needs access to CommonModule if it uses directives like *ngFor or *ngIf.
Here’s how you can add it:
// In your module file, usually app.module.ts or a feature module file import { CommonModule } from '@angular/common'; @NgModule({ declarations: [YourComponent], imports: [CommonModule], // Ensure CommonModule is imported here }) export class YourModule { }
Solution 2: Check Your Angular Directive Syntax
Incorrect Syntax: <div *ngForOf="let item in items">{{ item.name }}</div> Correct Syntax: <div *ngFor="let item of items">{{ item.name }}</div>
Solution 3: Ensure Your Collection is Defined
export class ListComponent { items: Array<{ name: string }> = [ { name: 'Item 1' }, { name: 'Item 2' }, { name: 'Item 3' }, ]; }
Solution 4: Confirm the Angular Version Compatibility
ng version
Solution 5: Restart the Angular Development Server
ng serve --open
Solution 6: Add Angular Language Service in the IDE
Some developers have found that this error is due to an issue with the IDE’s Angular language support rather than the actual Angular code.- Go to File > Settings > Plugins.
- Search for “Angular” and install Angular and AngularJS plugins.
- Go to the Extensions view.
- Search for “Angular Language Service” and install it.