ChatGPT解决这个技术问题 Extra ChatGPT

Can't bind to 'ngForOf' since it isn't a known property of 'tr' (final release)

I'm using Angular2 2.1.0. When I want to display a list of companies, I got this error.

in file.component.ts :

public companies: any[] = [
    { "id": 0, "name": "Available" },
    { "id": 1, "name": "Ready" },
    { "id": 2, "name": "Started" }
];

In file.component.html :

<tbody>
  <tr *ngFor="let item of companies; let i =index">
     <td>{{i}}</td>
     <td>{{item.name}}</td>
  </tr>
</tbody>
make sure you not made a typo too ngfor gives the error you mentioned. Should be ngFor
angular is case sensitive too.
Just lost ~1h on this error, on just one specific page. Tried all the answers here, but finally the solution was to rebuild the whole thing with ng, the problem just disappeared...
Sometimes it happens because of failed plugin in IDE (VS Code, Web Storm). Check my answer here: stackoverflow.com/a/70368326/4079915

G
Günter Zöchbauer

Add BrowserModule to imports: [] in @NgModule() if it's the root module (AppModule), otherwise the CommonModule.

// older Angular versions
// import {BrowserModule, CommonModule} from '@angular/common';

import { BrowserModule } from '@angular/platform-browser'
..
..
@NgModule({
  imports: [BrowserModule, /* or CommonModule */],
  ..
})

yes I have multiple Modules. I forgot this. It works now :) thank u
It might be worth mentioning that the CommonModule is located in '@angular/common' so you must make sure to add import {CommonModule} from '@angular/common'
I had similar issue. my app has multiple modules, the import Browser module statement needs to be added in app module and in another module.
sometimes it can be a simple typo, the same error happens when doing "*ngFor="let passenger or passengers" <--- notice: "or" should be "of" ;-)
In the new version of Angular the BrowserModule is part of @angular/platform-browser. Therefor, you must import as: import { BrowserModule } from '@angular/platform-browser'
M
Mr_Green

In my case, the issue was that my teammate mentioned *ngfor in templates instead of *ngFor. Strange that there is no correct error to handle this issue (In Angular 4).


well that could have thrown me for a loop ;)
Similar: I wrote *ngFor="let diagram if diagrams", notice the if. A "parse error" message would be better...
@klenium, you saved my day! i got that error when using *ngFor="lang in languages" where angular 8 expects *ngFor="let lang of languages". Pretty misleading error message imo :/
I got this error because I capitalized "let."
I made the same mistake, and did'n see it, luckly i found this very quickly, Tks
D
David Wolf

You have to import CommonModule in the module where you are using these in-built directives like ngFor, ngIf, etc.

import { CommonModule } from '@angular/common'
       
@NgModule({
    imports: [
        CommonModule
    ]
})
    
export class ProductModule { }

you say import it in the component, then show code importing it into the module
You are correct. Some directives, including ngfor, are within this module.
Worked for me. :)
W
WasiF

There can be any possible reason:

Your module does not have CommonModule in imports[] Your component, where you are using *ngFor or *ngIf is not a part of any module. You might have typo in *ngFor i.e. **ngFor or *ngfor etc. If everything seems fine then restart your app i.e. ng serve or IDE i.e. VS Code, IntelliJ etc.


Your module does not have CommonModule in imports[], worked for me as i haven't added commonmodule in my productmodule file
Superb. forgot to add component in declaration array.
This is the answer, which covers all possible reasons for the problem. For me worked no. 2. Thanks!
restart VS code or stop npm start and start it again worked for me.
for example something like this { path: 'items', loadChildren: () => import('./items/items.routing.module').then(m => m.ItemsRoutingModule) } when it needs to be { path: 'items', loadChildren: () => import('./items/items.module').then(m => m.ItemsModule) }
R
Ruben Szekér

For me the problem was that I did not import the custom made module HouseModule in my app.module.ts. I had the other imports.

File: app.module.ts

import { HouseModule } from './Modules/house/house.module';

@NgModule({
  imports: [
    HouseModule
  ]
})

Just spent over 1 hour looking for this solution. Thanks man!
Also consider relaunching 'ng serve' as sometimes new code additions are not properly picked up.
M
Max Mumford

This can also happen if you don't declare a route component in your feature module. So for example:

feature.routing.module.ts:

...
    {
        path: '',
        component: ViewComponent,
    }
...

feature.module.ts:

     imports: [ FeatureRoutingModule ],
     declarations: [],

Notice the ViewComponent is not in the declarations array, whereas it should be.


Thanks man, this wasn't my issue but it gave me a hint and bingo, my problem is solved!!
Thanks a lot! This solved my problem
This solved my issue and saved a lot of my time :)
R
Rut Shah

Things to remember:

When custom modules are used (modules other than AppModule) then it is necessary to import the common module in it.

yourmodule.module.ts

import { CommonModule } from '@angular/common';

@NgModule({
  imports: [
    CommonModule
  ],
  exports:[ ],
  declarations: []
})

Do you know why i would get that error/warning actually in chrome even after i have the commonModule on my child/custom module class?
M
Malcolm Swaine

I received the error because the component I was using wasn't registered in the declarations: [] section of the module.

After adding the component the error went away. I would have hoped for something less obscure than this error message to indicate the real problem.


Oh thanks, I've created an additional component in an existing .ts file and forget to register it because everything worked until I got this error.
I accidentally put my component in the providers: [] section. facepalm
B
Ben Winding

Future Readers

Check each of the following:

The component is declared in a SINGLE angular module Make sure you have import { CommonModule } from '@angular/common'; Restart the IDE/editor Restart the dev server (ng serve)


Just adding CommonModule doesn't fixed the issue, restarting Intelij IDE also was needed.
Also consider relaunching 'ng serve' as sometimes new code additions are not properly picked up.
restarting the server did it for me
A
Akshay Sharma

I was getting the same error, You can fix through one of this method:

If you don't have any nested module a. Import the CommonModule in your App module b. Import your Component where you are adding the *ngFor in the App Module, define in declarations

// file App.modules.ts
@NgModule({
  declarations: [
    LoginComponent // declarations of your component
  ],
  imports: [
    BrowserModule
    DemoMaterialModule,
    FormsModule,
    HttpClientModule,
    ReactiveFormsModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production })
  ],
  providers: [
    ApiService, 
    CookieService, 
    {
      provide: HTTP_INTERCEPTORS,
      useClass: ApiInterceptor,
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})

c. If you are using the separate module file for routing then Import the CommonModule in your Routing module else Import the CommonModule in your App module

// file app.routing.modules.ts
import { LoginComponent } from './login/login.component';
import { CommonModule } from "@angular/common";

const routes: Routes = [
  { path: '', component: LoginComponent },
  { path: 'login', component: LoginComponent }
];

@NgModule({
  imports: [RouterModule,RouterModule.forRoot(routes), CommonModule],
  exports: [RouterModule]
})

If you have nested module then perform the 1st step in that particular module

In my case, the 2nd method solved my issue. Hope this will help you


Indeed, I forgot to declare the component in my module.
A
Alok Kamboj

If you are making your own module then add CommonModule in imports in your own module


Adding CommonModule worked for me Please improve your answer. Share steps as well
Thank you, that was the reason. I would like to add that I had to restart the server
Also make sure that you custom module are in the declaration brackets
L
Lokesh G

Add the component to your app.module

import { ModalComponent } from './modal/modal.component';

@NgModule({
  declarations: [ModalComponent],
  entryComponents: [ModalComponent],
  
  }),
  providers: [
  ],
  bootstrap: [AppComponent]
})

Z
Ziv Barber

For Angular 10:

Add BrowserModule to the imports of your routes module. Make sure that you added the component that not working to the app module declarations.

Failing to do step 2 will trigger this error!

Make sure to RESTART ng serve !!!


A
Ahmad Alfy

Just in case someone still facing an error after trying to import CommonModule, try to restart the server. It surprisingly work


Just the first time. If I save, then the compailer reload and the problem still be there
A
Abhinav Saxena

So please make sure

No syntax error in directives Browser (in App Module) and Common (in other/child) Modules are imported (Same what Günter Zöchbauer mentioned above) If you've routes in the application then route module should be imported in App Module All the routed component's Module are also imported in App Module, for eg: app-routing.module.ts is as follows: const routes: Routes = [ {path: '', component: CustomerComponent}, {path: 'admin', component: AdminComponent} ];

Then App module must imports modules of CustomerComponent and AdminComponent in @NgModule().


E
Ermal

A lot of answers seem to converge by importing CommonModule in other(new/custom) modules.
This step only isn't enough in all situations.

The full solution consist in two steps:

Make directives NgIf, NgFor etc visible to your project. Reassemble everything in a correct way in the main component (app.module.ts)

Point 1
BrowserModule in main module seems to be enough for having access to NgFor. Angular Documentation stands it here: .

CommonModule Exports all the basic Angular directives and pipes, such as NgIf, NgForOf, DecimalPipe, and so on. Re-exported by BrowserModule,

See also accepted answer here: CommonModule vs BrowserModule in angular

Point 2 The only changes needed (in my case) are the followings:

import Module OtherModule import Component OtherComponent ng build (important!) ng serve

app.module.ts

@NgModule({
    imports: [
        BrowserModule,
        OtherModule
    ],
    declarations: [OtherComponent, AppComponent],
    bootstrap: [AppComponent]
})
export class AppModule {
}

other.html

<div *ngFor='let o of others;'> 
</div>

other.component.ts

@Component({
    selector: 'other-component',
    templateUrl: './other.html'
})
export class OtherComponent {
}

app.module.ts

@NgModule({
    imports: [],
    providers: []
})
export class OtherModule{
}

This helped me figure out the issue. I was missing the declaration in app.module.ts. Now it works. Thanks!
M
Maddy

After using correct syntax in all of your code, please see if you have mentioned your component in the declarations of your angular module. Something like below:

@NgModule({ declarations: [ AppComponent, YourComponent ],


Y
Yudner

I had the same problem, even though I had imported "BrowserModule" and "CommonModule" in "module.ts" it didn't work, my error was, not adding in "NgModule.declarations" my Component.

@NgModule ({
   declarations: [
     Your_Component // here
   ]
}) 

s
scsx

I had the same error but I had the CommonModule imported. Instead I left a comma where it shouldn't be because of copy/paste when splitting a module:

@NgModule({
    declarations: [
        ShopComponent,
        ShoppingEditComponent
    ],
    imports: [
        CommonModule,
        FormsModule,
        RouterModule.forChild([
            { path: 'shop', component: ShopComponent }, <--- offensive comma
        ])
    ]
})

S
Sanjay kumar

app.module.ts fixed and changed to: import the BrowserModule in your app module

import { BrowserModule } from '@angular/platform-browser';

@NgModule({
  declarations: [
    AppComponent    
  ],
  imports: [
    BrowserModule, 
  ],     
  providers: [],
  bootstrap: [AppComponent]
})

A
Alexei - check Codidact

I have encountered a similar error (*ngIf) even if all my imports were OK and the component was rendered without any other error + routing was OK.

In my case AppModule was not including that specific module. The strange thing is that it did not complain about this, but this might be related with how Ivy works with ng serve (kind of loads modules according to routing, but its dependencies are not considered).


A
Ahmad Alfy

Custom Module Needs common module

import { CommonModule } from "@angular/common";


@NgModule({
  imports: [
    CommonModule
  ]
})

M
Mohamed Ali

if you already imopted (BrowserModule, CommonModule, FormsModule) and its still not working

then all you have to do is check if the component that has the error is declared in the module


J
Juan Carlos WebMaster Ajahuana

When use "app-routing.module" we forget import "CommonModule". Remember to import!

import { CommonModule } from "@angular/common";
@NgModule({  imports: [ CommonModule]})

N
Nagnath Mungade

I am started on Angular8 base live project got the above issue but When use "app-routing.module" we forget import "CommonModule". Remember to import!

import { CommonModule } from '@angular/common';

@NgModule({
  imports: [
    CommonModule
]})

It will solve your error.


s
sunleo

I had a problem because of ** instead *

*ngFor="let ingredient of ingredients"

**ngFor="let ingredient of ingredients"

Yep, VS Code seems to automatically put two stars instead of a single one.
J
JeffryHouser

For future reference, I'm doing some unit testing on Angular 12 and ran into this.

My issue was that I was using the ng bootstrap library and testing a method that was creating a new modal with NgbModal.

I was getting these warnings because I had forgotten to import the component being created by the popup.

I did not need to import FormsModule, CommonModule, or BrowserModule.

So, if you run into these errors make sure that the component you're trying to create an instance of is listed in the imports.


C
Chamath Jeevan

If you have module implementation, then you must import the component and set the component in the declaration

https://i.stack.imgur.com/jXu6c.png

Good Luck on your coding :)


D
Daniel Methner

Just had the same issue after modifying a couple of components. There was no syntax error and all modules were imported, but a restart of the server fixed the issue. The error occurred in a component, that was added several dozen successful commits ago.

Just in case someone else experiences the same issue.


J
John

I think my scenario is a rare case, but I will answer anyway.

I didn't have any syntax errors, I imported BrowserModule, I restated my IDE (VS Code), but I still got red lines in my template because I used *ngFor.

I happened because I was using an extension, Angular Language Service, but it was quite old. After updating it, the error stopped appearing.

https://i.stack.imgur.com/0yjUh.png