'NgIf' is neither 'ComponentType' or 'DirectiveType'

Viewed 1867

When using *ngIf in a very simple component, I get the error in the title. For example, below code and app.module cause this:

app.component.html:

<ng-container *ngIf="true">
  <div>True</div>
</ng-container>

app.module.ts:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';

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

I am very confused as to what could be causing this. *ngFor directive has the same problem. The rest of the project comes directly from ng new generated files.

"@angular/core": "~11.2.8"

2 Answers

A corrupted or otherwise weird node_modules is most likely the source of the problem.

Running npm ci fixes the problem.

That is because NgIf is declared in common module

Add & import the module in your app module or any other module that wants to utilize common directives.

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

This is very common mistake when people forget to import the things they require in angular runtime, since each module imports and exports their own set of object, you need to specify what needs to be done and at the end compiler will shake tree to import necessary modules and class code with chunks.

NgIf Directive Documentation states that to use the modifier you need commons module

so your code should look like :

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
],
  imports: [
    CommonModule,
    BrowserModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
Related