Back to all posts

Angular: How to create components


When creating an angular component, you have two primary options: using the Angular CLI (Command Line Interface) or creating the component manually. Below is a comparison of both approaches.

Manual Creation

Create the component files manually:

  • <component-name>.component.ts
  • <component-name>.component.html
  • <component-name>.component.css
  • <component-name>.component.spec.ts

Using Angular CLI

Open the terminal in your Angular project directory.

Run the command:

ng generate component <component-name>

Or shorthand

ng g c <component-name>

Write the component code in component.ts

import { Component } from "@angular/core"; 

@Component({
    selector: 'app-header',
    standalone:true, 
    templateUrl: './header.component.html'
})

export class HeaderComponent {}

Declare the component in the appropriate Angular module (app.module.ts):

import { Component } from '@angular/core';
import { HeaderComponent } from './header.component';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [HeaderComponent],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css',
})
export class AppComponent {}