javascriptangulartypescriptangular-module

Angular "ng generate" does not create a module automatically


i created an angular project, used ng generate to put the necessary file but it did not give me a module automatically, and when i try to add a module and serve it keeps saying "TS-996008: Component AppComponent is standalone, and cannot be declared in an NgModule. Did you mean to import it instead?"

i was expecting to have a module that was attached to the main.ts file

import { Component, OnInit, enableProdMode } from '@angular/core'; // here we're importing the component decorator and an interface called onInit
import { RouterOutlet } from '@angular/router';

enableProdMode();
@Component({ //this is a decorator boyyyy
  selector: 'app-root', // used as the main startup component thats why its called root instead of app-component, because its the first thing that'll run when we load the page
  standalone: false,
  imports: [RouterOutlet],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent implements OnInit { //onInit is an interface that angular provides and when implemented you must add the function below 'ngOninit'
  title = 'angularDemo using databinding biatch';

  // title: string; //we use this for ngOninit when we want to use it to call a service that sets the title and assigning it as a string
  constructor() {}

  ngOnInit() {
    // this is an example of using onInit here "in our imagination" we call a service that sets the title
    // this.title = 'angularDemo using databinding';
  }
}

above is my component code


Solution

  • What version of angular are you using ? Bcs it looks like that you are working with angular 17 where the concept of standalone components was introduced. Components can be marked as standalone or they are marked as standalone by default, meaning they do not need to be declared in an NgModule.

    If you don't want a standalone component, it's enough to remove the standalone property in the component or change true to false.

    @Component({
      selector: 'app-example',
      templateUrl: './app-example.component.html',
      styleUrls: ['./app-example.component.scss'],
      standalone: true
    })
    

    So if you want to generate component which is not standalone

    ng generate component --standalone false
    

    Or if you want default behavior like to be standalone for each generate comand. You need to implement change in angular.json

      "projects": {
        "my-angular17-project": {
          "projectType": "application",
          "schematics": {
            "@schematics/angular:component": {
              "style": "scss",
              "standalone": false
            }
          },
        }
    }