CPCODELAB
Angular

Components and @Component

12 min read

The Building Block: Angular Components

A component is the core UI primitive in Angular. Each component combines a TypeScript class (logic), an HTML template (view), and optional CSS styles. The @Component decorator marks a class as a component and links the three pieces together.

ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-greeting',
  standalone: true,
  template: `
    <h1>Hello, {{ name }}!</h1>
    <button (click)="greet()">Greet</button>
  `,
  styles: [`
    h1 { color: #dd0031; }
  `]
})
export class GreetingComponent {
  name = 'Angular';

  greet() {
    alert('Hello from ' + this.name);
  }
}

Key @Component Properties

  • selector — the HTML tag used to place this component (<app-greeting>)
  • standalone: true — component does not need an NgModule
  • template / templateUrl — inline HTML or path to an external file
  • styles / styleUrl — inline CSS array or path to a stylesheet
  • imports — other standalone components, directives, pipes this component needs

To use a standalone component inside another, add it to the imports array of the host component's @Component decorator. This replaces the older NgModule-based declaration system and makes dependency relationships explicit and local.

ts
import { Component } from '@angular/core';
import { GreetingComponent } from './greeting.component';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [GreetingComponent],
  template: `<app-greeting />`
})
export class AppComponent {}

Standalone components are the recommended default in Angular 17+. NgModules still exist and work, but you will rarely need them for new projects.

Ready to test yourself?
Practice Angular— quiz & coding exercises