0
0
AngularHow-ToBeginner · 3 min read

How to Use ng generate component in Angular CLI

Use the Angular CLI command ng generate component <component-name> to create a new component with all necessary files and boilerplate. This command sets up the component folder, TypeScript, HTML, CSS, and test files automatically.
📐

Syntax

The basic syntax for creating a component is:

  • ng generate component <component-name>: Creates a new component with the given name.
  • You can add options like --inline-style or --inline-template to customize file generation.
  • Use --skip-tests to avoid creating test files.
bash
ng generate component <component-name> [options]
💻

Example

This example creates a component named user-profile. It generates a folder user-profile with four files: user-profile.component.ts, user-profile.component.html, user-profile.component.css, and user-profile.component.spec.ts.

bash
ng generate component user-profile
Output
CREATE src/app/user-profile/user-profile.component.ts (270 bytes) CREATE src/app/user-profile/user-profile.component.html (23 bytes) CREATE src/app/user-profile/user-profile.component.css (0 bytes) CREATE src/app/user-profile/user-profile.component.spec.ts (614 bytes)
⚠️

Common Pitfalls

Common mistakes include:

  • Not running the command inside an Angular project folder, which causes errors.
  • Using invalid component names with spaces or special characters.
  • Forgetting to import the new component in a module if --skip-import is used.

Always check the console output for errors and verify the component is declared in the right module.

bash
Wrong:
ng generate component user profile

Right:
ng generate component user-profile
📊

Quick Reference

OptionDescription
--inline-styleInclude CSS inside the component TS file instead of a separate CSS file.
--inline-templateInclude HTML inside the component TS file instead of a separate HTML file.
--skip-testsDo not create the test spec file.
--flatCreate the component files in the current folder without a subfolder.
--skip-importDo not add the component to the nearest module automatically.

Key Takeaways

Use ng generate component <name> inside an Angular project to create a new component with all files.
Component names should be lowercase and hyphen-separated without spaces or special characters.
Options like --inline-style and --skip-tests customize the generated files.
Always verify the new component is declared in the appropriate Angular module.
Run the command in the project root or a subfolder to avoid errors.