Angular: Create a Component with Angular CLI

Learn how to create an Angular Component using the Angular CLI.

Prerequisites

  1. Install Angular CLI

The Short Version

1. Run this command from your shell:

ng g c components/Header

This creates a new Component called HeaderComponent in the folder src/app/components/header/.

The Details

In Angular, the Typescript, HTML, and CSS used to render a piece of a web application can be grouped together into a unit called a Component.

We are going to create a Component called HeaderComponent. It will display a bar with navigation links at the top of every page in the application.

We will use Angular CLI to generate all of the files needed for the HeaderComponent:

1. Run this command* from your shell:

ng generate component components/Header

This command does the following:

  • Creates a new folder header/ in the folder src/app/components/. Within the header/ folder, it also creates:
    • the file header.component.html, where the Component’s HTML lives.
    • the file header.component.ts, where the Component’s Typescript lives.
    • the file header.component.spec.ts, where the Component’s unit tests live.
    • the file header.component.css, where the Component’s CSS lives.
  • Adds HeaderComponent to the declarations of your NgModule in src/app/app.module.ts. This makes the web application aware of the existence of HeaderComponent.

*You can use the shorthand version of the command to perform the exact same action. You can use “g” instead of “generate” and “c” instead of “component”:

ng g c components/Header

Next

Right now, our HeaderComponent doesn’t do much. In fact, it is not even visible to the user. We will learn how to get it to display in our web application in the next article.

Versions: Angular CLI: 9.1.4