Search code examples
angulartypescriptangular-ng-if

Error when using ngIf on div in a submodule in Angular


I have an app that is using mostly components, but I created my own submodule, named ProjectsModule. This ProjectsModule is using its own router and so on, but the issue is when displaying a specific component of this module, I get:

NG0303: Can't bind to 'ngIf' since it isn't a known property of 'div'.

The component project-list.component.html that has the issue:

<div class="projects" *ngIf="projects">
  <app-project-bloc *ngFor="let project of projects"
                    [project]="project"
                    [routerLink]="[project.shortname]"
  ></app-project-bloc>
</div>

The ProjectModule:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import {ProjectListComponent} from "./pages/project-list/project-list.component";
import {ProjectBlocComponent} from "./components/project-bloc/project-bloc.component";
import {ProjectPageComponent} from "./pages/project-page/project-page.component";
import {RouterModule} from "@angular/router";

@NgModule({
  declarations: [
    ProjectListComponent,
    ProjectBlocComponent,
    ProjectPageComponent
  ],
  imports: [
    CommonModule,
    RouterModule
  ]
})
export class ProjectsModule { }

And the AppModule:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { LandingComponent } from './components/landing/landing.component';
import { MenuComponent } from './components/menu/menu.component';
import { CareerComponent } from './components/career/career.component';
import { GetInTouchComponent } from './components/get-in-touch/get-in-touch.component';
import { WritingsComponent } from './components/writings/writings.component';
import {CommonModule} from "@angular/common";
import {ProjectsModule} from "./components/projects/projects.module";

@NgModule({
  declarations: [
    AppComponent,
    LandingComponent,
    MenuComponent,
    CareerComponent,
    GetInTouchComponent,
    WritingsComponent,
  ],
  imports: [
    CommonModule,
    BrowserModule,
    AppRoutingModule,
    ProjectsModule
  ],
  providers: [],
  exports: [
    BrowserModule
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

I believe I imported correctly the BrowserModule and CommonModule, so what am I doing wrong here?


Solution

  • *If and *For in a nested DOM element is a tricky thing since ngV2.

    I'd recommend <ng-container>

    something like that

    <ng-container *ngIf="projects>
      <div *ngFor="let thing of stuff">
        etc. etc.
        <span>{{thing.name}}</span>
      </div>
    </ng-container>
    

    good luck!