Angular:从ng-for向ng-template传数组对象时报错,已引CommonModule仍无解
Hey there! I’ve run into this exact frustrating issue before, so let’s break down why this error is still sticking around and how to fix it step by step.
First, Double-Check Which Module Your Component Lives In
You mentioned adding CommonModule to AppModule, but if your component is part of a feature module (not directly declared in AppModule), that’s probably the root cause! CommonModule needs to be imported into every module that uses directives like *ngFor, ngTemplateOutlet, or ngTemplateOutletContext—it doesn’t cascade down from AppModule to feature modules.
For example, if your component is in ProductModule, add CommonModule there too:
@NgModule({ imports: [CommonModule], // This is mandatory here! declarations: [YourProblemComponent], exports: [YourProblemComponent] // Only if you need to use this component outside the module }) export class ProductModule { }
If you’re using standalone components (Angular 14+), you have to import CommonModule directly in the component’s imports array instead of a module:
@Component({ selector: 'app-your-component', standalone: true, imports: [CommonModule], // Critical for standalone components to access Angular directives templateUrl: './your-component.component.html' }) export class YourComponent { }
Verify Your Template Syntax (and Angular Version)
Make sure you’re using the correct syntax to pass the array object from your *ngFor loop to the ng-template. Here’s a working example:
Option 1: Using explicit [ngTemplateOutlet] and [ngTemplateOutletContext]
<!-- Loop through your array of objects --> <ng-container *ngFor="let item of yourArray"> <!-- Pass the current item to the template using $implicit --> <ng-container [ngTemplateOutlet]="itemTemplate" [ngTemplateOutletContext]="{ $implicit: item }" ></ng-container> </ng-container> <!-- Define your template, use let-item to receive the passed object --> <ng-template #itemTemplate let-item> <div>Item Name: {{ item.name }}</div> <div>Item Description: {{ item.description }}</div> </ng-template>
Option 2: Shorthand *ngTemplateOutlet syntax
If you prefer a more concise version, use the star syntax with the context parameter:
<ng-container *ngFor="let item of yourArray"> <ng-container *ngTemplateOutlet="itemTemplate; context: { $implicit: item }"></ng-container> </ng-container> <ng-template #itemTemplate let-item> <!-- Same content as above --> </ng-template>
Note: If you’re on Angular 14+, ngTemplateOutletContext is still supported, but you’ll often see docs recommending the context parameter in the shorthand syntax—both work, just don’t mix up the two styles.
Don’t Forget to Check for Typos!
It sounds obvious, but double-check that you spelled ngTemplateOutletContext correctly. Missing a letter (like ngTemplateOutletContex without the final t) or incorrect capitalization will throw this exact error every time.
内容的提问来源于stack exchange,提问作者Sannu

