Sub topic 10
Generating components, services and more with ng generate
This chapter assumes you have created a workspace with ng new, you know what src/app and angular.json contain, and you can read basic TypeScript decorators. It covers how ng generate works, which artifacts it produces, which options matter, and which mistakes beginners make most often.
What ng generate does
ng generate (alias ng g) runs a schematic. A schematic is a small program that reads your workspace and then creates or edits files. The built-in schematics come from the @schematics/angular package.
A schematic does three things:
- It finds the target project in
angular.jsonand the folder to write into. - It renders file templates, with names converted into the right case (
product-list,ProductList,productList). - It may edit existing files, for example to add a route or an import.
The command has this shape:
ng generate <schematic> <name> [options]The name can include a path. In ng generate component products/product-list, the CLI creates the product-list folder inside src/app/products. The products folder is created if it does not exist.
Generating a component
ng generate component products/product-listDepending on the CLI version, this produces files like these in src/app/products/product-list/:
| File | Purpose |
|---|---|
| `product-list.component.ts` | The component class and its `@Component` metadata |
| `product-list.component.html` | The template |
| `product-list.component.css` | Styles for this component (the extension follows the stylesheet format you chose in `ng new`) |
| `product-list.component.spec.ts` | A unit test file |
Newer CLI versions drop the .component part of the file name and the Component suffix of the class. You get product-list.ts and a class named ProductList. The older and newer styles both work. Check the generated class name before you import it elsewhere.
A generated component is standalone. It declares its own imports and does not belong to an NgModule:
import { Component } from '@angular/core';
@Component({
selector: 'app-product-list',
imports: [],
templateUrl: './product-list.component.html',
styleUrl: './product-list.component.css',
})
export class ProductListComponent {}The selector starts with app- because of the prefix setting for the project in angular.json. Change that setting if you want a different prefix.
Where the component goes
A standalone component is not registered anywhere. To use it, you import it in the imports array of another standalone component and then write its selector in that component's template:
import { Component } from '@angular/core';
import { ProductListComponent } from './products/product-list/product-list.component';
@Component({
selector: 'app-root',
imports: [ProductListComponent],
template: `<app-product-list />`,
})
export class AppComponent {}Or you can reference it from a route in app.routes.ts. Forgetting the imports entry is the most common error. Angular reports an unknown element for app-product-list, and the build can fail or warn.
Generating a service
ng generate service products/productThis creates product.service.ts and product.service.spec.ts. The class is decorated for root-level injection:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class ProductService {}providedIn: 'root' registers one shared instance for the whole application, so you do not add it to any providers array. In a component you obtain it with inject(ProductService).
Other common schematics
| Schematic | Shortcut | What it creates |
|---|---|---|
| `component` | `c` | A component |
| `service` | `s` | An injectable service |
| `directive` | `d` | An attribute or structural directive |
| `pipe` | `p` | A template pipe |
| `guard` | `g` | A route guard (the CLI asks which type) |
| `interceptor` | none | An HTTP interceptor function |
| `interface` | `i` | A TypeScript interface |
| `enum` | `e` | A TypeScript enum |
| `class` | `cl` | A plain class |
| `resolver` | `r` | A route resolver |
| `environments` | none | Environment files and build file replacements |
Run ng generate --help to list the schematics available in your installation. Libraries you add with ng add can contribute their own schematics, and they appear in the same list.
Options that matter
Options go after the name. These are the ones you will use most:
| Option | Effect |
|---|---|
| `--dry-run` (or `-d`) | Print what would be created or changed and write nothing |
| `--skip-tests` | Do not create the `.spec.ts` file |
| `--inline-template` (`-t`) | Put the template inside the `.ts` file |
| `--inline-style` (`-s`) | Put the styles inside the `.ts` file |
| `--flat` | Do not create a folder for the artifact |
| `--change-detection OnPush` (`-c`) | Set the change detection strategy |
| `--project` | Choose the project in a multi-project workspace |
| `--prefix` | Override the selector prefix |
| `--force` (`-f`) | Overwrite files that already exist |
Use --dry-run before any generation you are not sure about:
ng generate component products/product-detail --dry-run --inline-template --skip-testsThe output lists lines such as CREATE src/app/products/product-detail/product-detail.component.ts. Nothing is written to disk.
Be careful with --force. It replaces existing files without a prompt, so commit your work first.
How the CLI picks the location
The CLI resolves the target folder in this order:
- If you pass a path in the name, it uses that path relative to the project's source root.
- If you run the command from inside a subfolder of the project, it uses the current folder as the base.
- Otherwise it uses the project's
sourceRootplusapp.
This means the same command can create files in different places depending on your working directory. If you run ng g c product-list while inside src/app/products, the component lands in src/app/products/product-list. Running it from the workspace root puts it in src/app/product-list. Use --dry-run to check.
Project-wide defaults
You can set defaults for schematic options in angular.json under schematics. This saves you from typing the same flags each time:
{
"projects": {
"my-app": {
"schematics": {
"@schematics/angular:component": {
"changeDetection": "OnPush",
"skipTests": false,
"style": "css"
}
}
}
}
}The key is the schematic's collection and name. Options on the command line override these defaults. The ng new command writes some of these entries for you when you choose options such as the stylesheet format.
Edits the CLI makes to existing files
Most schematics only add files. A few also edit others:
- Generated guards and resolvers do not register themselves. You attach them to routes by hand.
- The
environmentsschematic addsfileReplacementsentries toangular.json. - Libraries installed with
ng addmay modifyapp.config.ts,main.tsorangular.json.
Because of this, read git diff after running a schematic you have not used before.
Common errors
- "Could not find an NgModule": you are using an old tutorial or an option that targets modules. Standalone is the default, so remove module-related flags.
- Files in the wrong folder: you ran the command from a subfolder. Check your working directory.
- "Unknown element" in the browser console or build output: the component is not in the
importsarray of the component that uses it. - Selector mismatch: you changed
prefixafter generating components. Existing components keep their old selectors. - Name collisions: if the file exists, the CLI refuses to overwrite it unless you pass
--force.
Workflow summary
Practice
Exercise
You are in the src/app/products folder and run ng g c product-list --dry-run. Where will the component be created, and what changes if you run the same command from the workspace root?
Show answer
From inside src/app/products, the CLI uses the current folder as the base and plans files in src/app/products/product-list/. From the workspace root it uses src/app, so the files go in src/app/product-list/. --dry-run only prints the plan, so nothing is written in either case.
Exercise
A new standalone component compiles, but its tag renders nothing and the console reports an unknown element. What is the likely cause and the fix?
Show answer
The component was generated but never imported by the component that uses its selector. Add the class to the imports array of the parent standalone component (or route to it from app.routes.ts).
Exercise
How would you make every new component in a project use OnPush change detection without typing a flag each time?
Show answer
Add a schematics entry to the project in angular.json: "@schematics/angular:component": { "changeDetection": "OnPush" }. Command-line options still override it.