A2oz

How to Generate a Component in Angular Command Line?

Published in Angular Development 2 mins read

Generating Angular components is a simple process using the Angular CLI. Here's how you can do it:

1. Open your Terminal or Command Prompt

Navigate to the root directory of your Angular project using the cd command.

2. Use the ng generate Command

Type the following command in your terminal:

ng generate component <component-name>

Replace <component-name> with the desired name for your new component. For example, to create a component named 'my-component', you would use:

ng generate component my-component

3. Review the Generated Files

The Angular CLI will create a new folder with the component name. This folder will contain the following files:

  • <component-name>.component.ts: This file contains the component's logic and data.
  • <component-name>.component.html: This file defines the component's template.
  • <component-name>.component.css: This file contains the component's styles.

4. Use the Component

You can now use the newly generated component in your Angular application.

Example:

Let's say you have a component named my-component. You can use it in your app.component.html file like this:

<app-my-component></app-my-component>

This will render the my-component within the app.component.html template.

Additional Notes:

  • You can use the --spec flag to generate a test file for the component. For example:
      ng generate component my-component --spec
  • You can use the --inline-style flag to include the component's styles within the template file. For example:
      ng generate component my-component --inline-style

By following these steps, you can easily generate new components for your Angular applications.

Related Articles