249

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>
luiscla27
  • 4,956
  • 37
  • 49
Mourad Idrissi
  • 3,455
  • 5
  • 17
  • 29

41 Answers41

347

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 */],
  ..
})
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Is it your only module or do you have more than one? `BrowserModule` is only for the root module. – Günter Zöchbauer Oct 30 '16 at 17:23
  • Can you reproduce in a Plunker? (Plunker provides a ready to use Angular2 TS template). – Günter Zöchbauer Oct 30 '16 at 17:23
  • 6
    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' – knsheely Jun 12 '17 at 18:02
  • 5
    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. – ssmsnet Sep 12 '17 at 14:18
  • @ssmsnet Importing `BrowserModule` in other modules than `AppModule` is invalid. In other modules `CommonModule` needs to be imported. You should get an error message if you import `BrowserModule` in other modules. – Günter Zöchbauer Sep 12 '17 at 14:20
  • I needed to import `BrowserModule` in a child module to get the `*ngFor` directive working, and I had it in the root too. `CommonModule` is the correct one to import tho, but both modules worked in my child module. No compile error (with angular `5.0.5`) – Sean Newell Dec 14 '17 at 15:11
  • I don't think there was a related change. You should get an error https://github.com/angular/angular/blob/5.1.1/packages/platform-browser/src/browser.ts#L95 – Günter Zöchbauer Dec 14 '17 at 15:44
  • 2
    sometimes it can be a simple typo, the same error happens when doing "*ngFor="let passenger or passengers" <--- notice: "or" should be "of" ;-) – michabbb Feb 08 '19 at 10:57
  • 2
    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'` – Ramin Ar Oct 27 '19 at 14:36
  • N.b.: If you get that warning in a unit test, even though you have imported the `CommonModule`, check for dynamically loaded components and ensure that those are also added to your test harness. The compiler possibly omits the `CommonModule` when it is only used in a dynamic component (due to tree shaking). – 1FpGLLjZSZMx6k Apr 18 '20 at 15:44
  • 2
    I had similar issue, But even after trying this it was still not working! I have multiple modules, I forgot to import the "other module" into my "root module" and that was breaking a few of my imports including the `CommonModule` and it was giving me this same error. Thanks for you @Günter this helped me narrow it down and find my real problem. Hope this extra info helps some one, I spent hours trying to find the problem, dooh. – brayden Prestwich Feb 16 '21 at 22:08
86

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).

Mr_Green
  • 40,727
  • 45
  • 159
  • 271
75

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 { }
David Wolf
  • 1,400
  • 1
  • 9
  • 18
Codiee
  • 3,047
  • 2
  • 17
  • 18
63

There can be any possible reason:

  1. Your module does not have CommonModule in imports[]
  2. Your component, where you are using *ngFor or *ngIf is not a part of any module.
  3. You might have typo in *ngFor i.e. **ngFor or *ngfor etc.
  4. If everything seems fine then restart your app i.e. ng serve or IDE i.e. VS Code, IntelliJ etc.
WasiF
  • 26,101
  • 16
  • 120
  • 128
  • 1
    Your module does not have CommonModule in imports[], worked for me as i haven't added commonmodule in my productmodule file – cracker Feb 17 '21 at 14:12
  • 5
    Superb. forgot to add component in declaration array. – Usman Saleh May 21 '21 at 06:49
  • 3
    This is the answer, which covers all possible reasons for the problem. For me worked no. 2. Thanks! – kappa Aug 23 '21 at 09:41
  • 3
    restart VS code or stop npm start and start it again worked for me. – AlignedDev Jan 27 '22 at 17:23
  • I had this error without anything wrong in the code. I just had to type (and delete) something in my templates, and it worked again. – Watchduck Apr 25 '22 at 20:58
  • @TimPerry you're welcome. but first would you please explain here in the comment section that what do you mean by sub-module and why we should import it in our main module. I hope to see your logical and solid reason solo for this error then we're good to add it. – WasiF Jun 03 '22 at 11:40
  • This are all good suggestion but for my case it was because i have given the path of the routing instead on the module class while lazy loading and it took me a while to figure it out – Hana Wujira Jun 16 '22 at 04:14
  • @HanaWujira can you share your code sample here in comment. – WasiF Jun 17 '22 at 06:05
  • 1
    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) } – Hana Wujira Jun 17 '22 at 07:34
30

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
  ]
})
Ruben Szekér
  • 1,065
  • 1
  • 10
  • 21
23

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.

Max Mumford
  • 2,482
  • 5
  • 28
  • 40
19

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.

Malcolm Swaine
  • 1,929
  • 24
  • 14
  • 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. – svarog Feb 04 '21 at 09:03
  • I accidentally put my component in the providers: [] section. *facepalm* – Isaac Lyman Jun 24 '21 at 20:16
  • Usually when you create a new component using ng g c 'component-name' , it registers the component in the app.module.ts. However if you open a new terminal and run the generate component command while ng serve is running on a different component, it will not register the component in the app.module.ts . This is what was causing my issue. – goodcat Apr 28 '23 at 16:48
15

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: []
})
Rut Shah
  • 1,093
  • 11
  • 13
  • 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? – Ak777 Jul 10 '20 at 09:39
14

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

  1. 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]
})
  1. 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

Akshay Sharma
  • 1,042
  • 1
  • 8
  • 21
13

Future Readers

Check each of the following:

  1. The component is declared in a SINGLE angular module
  2. Make sure you have import { CommonModule } from '@angular/common';
  3. Restart the IDE/editor
  4. Restart the dev server (ng serve)
Ben Winding
  • 10,208
  • 4
  • 80
  • 67
8

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

Alok Kamboj
  • 1,017
  • 11
  • 12
5

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

Ahmad Alfy
  • 13,107
  • 6
  • 65
  • 99
5

Add the component to your app.module

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

@NgModule({
  declarations: [ModalComponent],
  entryComponents: [ModalComponent],
  
  }),
  providers: [
  ],
  bootstrap: [AppComponent]
})
Lokesh G
  • 831
  • 11
  • 19
5

In my case the component wasn't listed in app.module.ts.

PeterPazmandi
  • 533
  • 10
  • 13
4

For Angular 10:

  1. Add BrowserModule to the imports of your routes module.
  2. 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 !!!

Ziv Barber
  • 595
  • 9
  • 13
3

So please make sure

  1. No syntax error in directives

  2. Browser (in App Module) and Common (in other/child) Modules are imported (Same what Günter Zöchbauer mentioned above)

  3. If you've routes in the application then route module should be imported in App Module

  4. 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().

Abhinav Saxena
  • 3,384
  • 1
  • 11
  • 7
3

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:

  1. Make directives NgIf, NgFor etc visible to your project.
  2. 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:

  1. import Module OtherModule
  2. import Component OtherComponent
  3. ng build (important!)
  4. 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{
}
Ermal
  • 441
  • 5
  • 19
  • This helped me figure out the issue. I was missing the declaration in app.module.ts. Now it works. Thanks! – AjCodez Nov 03 '21 at 00:23
3

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 ],

Maddy
  • 503
  • 6
  • 17
3

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
   ]
}) 
Yudner
  • 533
  • 4
  • 9
2

Custom Module Needs common module

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


@NgModule({
  imports: [
    CommonModule
  ]
})
Ahmad Alfy
  • 13,107
  • 6
  • 65
  • 99
Vinayak Shedgeri
  • 2,222
  • 1
  • 21
  • 24
2

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
        ])
    ]
})
scsx
  • 21
  • 1
2

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]
})
Sanjay kumar
  • 1,653
  • 12
  • 18
2

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).

Alexei - check Codidact
  • 22,016
  • 16
  • 145
  • 164
2

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

2

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

enter image description here

Good Luck on your coding :)

Chamath Jeevan
  • 5,072
  • 1
  • 24
  • 27
1

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

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

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.

Nagnath Mungade
  • 921
  • 10
  • 11
1

I had a problem because of ** instead *

*ngFor="let ingredient of ingredients"

**ngFor="let ingredient of ingredients"
sunleo
  • 10,589
  • 35
  • 116
  • 196
1

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.

JeffryHouser
  • 39,401
  • 4
  • 38
  • 59
1

A bit late to the party, but I recently ran into this situation. This answer didn't solve my problem.

My premises

  • I was using a custom directory structure for the project. The offending component sits inside the components directory.

    My Directory Structure

  • The component where I found a similar error was created using CLI schematics with the
    --skip-import option

      npx ng g c --skip-import ../components/my-component
    

Solution

Because I used the --skip-import(see note) option, I found that my component was not added to the declarations array in my module. Adding the component to the same solved the problem.

Note : Well,you can't create the component outside the app directory without this.

sjsam
  • 21,411
  • 5
  • 55
  • 102
1

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.

Daniel Methner
  • 509
  • 1
  • 6
  • 18
1

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.

enter image description here

John
  • 10,165
  • 5
  • 55
  • 71
0

This error can also be thrown when the ngFor syntax isn't written correctly, in my case I had:

<ng-template *ngForOf="let key of SomeObject; index as i">

And it got fixed by using the following syntax:

<ng-template ngFor let-key [ngForOf]="SomeObject" let-i="index">
luiscla27
  • 4,956
  • 37
  • 49
0

I had a problem because of blank space in the json data.

user3727574
  • 136
  • 1
  • 8
0

In my case, the problem was, that I used const instead of let inside the *ngFor.

lilalinux
  • 2,903
  • 3
  • 43
  • 53
0

In my case, I already had CommonModule included in my shared module & the feature module where the component was to be used, but in my case I saved some files while server was starting (compiling) maybe that's why it did not took registry of included modules properly

=> I restarted my local server it solved the problem for me

0

I had imported CommonModule in the mycomponent.module.ts, and BrowserModule in the app.module.ts, added the MyComponent to @ngModule's declarations and reset vscode just like all the solutions had mentioned.

Finally resolved the issue by instead of iterating through data recieved through a fetch request, I mocked the elements array with hardcoded data matching the ElementModel.ts data And it worked no issues.

Realized that my ElementModel interface didn't match the data I was receiving from my fetch request.

Hope this helps someone.

0

I ran into this problem and for me the issue was that I had mistakenly named two components the same thing

Pytth
  • 4,008
  • 24
  • 29
0

If you face the error in angular version 14+ where a component can stand alone, just add NgFor to the imports of your component like this :

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

@Component({
selector     : 'my-component',
templateUrl  : './my-component.component.html',
encapsulation: ViewEncapsulation.None,
standalone   : true,
imports      : [ NgFor],
})

export class MyComponent implements OnInit
{
   ...
}
kplus
  • 694
  • 8
  • 31
0

In my case, when doing lazy loading I mistakenly let auto complete finish the import that imported the routing module instead of module

 {
    path: "list-management",
    loadChildren: () =>
      import(
        "./views/pages/list-management/list-management-routing.module"
      ).then((m) => m.ListManagementRoutingModule)
}

Then I changed that to correct module

    {
        path: "list-management",
        loadChildren: () =>
          import(
            "./views/pages/list-management/list-management.module"
          ).then((m) => m.ListManagementModule)
    }

 
Shrihari
  • 95
  • 2
  • 11
-2

For me, what solved the problem was to do a git clone of my project and run (as usual):

npm install
Sofía
  • 784
  • 10
  • 24