TExcelTAD
Home › Angular › Angular Components

Angular Components

A component is a reusable piece of UI: a TypeScript class that holds data and behaviour, a template that describes the HTML, and optional styles. Pages are built by nesting components inside each other — an App contains a Header, a TaskList and a Footer; a TaskList contains many TaskCards.

The @Component decorator

ts
@Component({
  selector: 'app-task-card',     // the HTML tag that places this component
  imports: [],                   // other components, directives and pipes used in the template
  templateUrl: './task-card.html',
  styleUrl: './task-card.css',
})
export class TaskCard { }
Option Purpose
selector CSS selector that tells Angular where to render the component; usually an element name with a prefix such as app-
template / templateUrl Inline HTML, or a path to an .html file
styles / styleUrl Inline CSS, or a path to a .css file (scoped to this component)
imports Everything the template uses that isn't plain HTML
changeDetection Optional strategy, covered in the Change Detection lesson

Note: Components are standalone by default in modern Angular. You don't need to declare them in an NgModule — you list them directly in the imports of the components that use them.

Creating and using a component

Generate a component with ng g c badge, or write it by hand. Here a small Badge is defined and then used twice inside App:

angular · try it yourself
import { Component } from '@angular/core';

@Component({
  selector: 'app-badge',
  template: `<span class="badge">NEW</span>`,
  styles: `
    .badge { background: #dd0031; color: #fff; font-size: 12px;
             padding: 2px 8px; border-radius: 10px; }
  `,
})
export class Badge {}

@Component({
  selector: 'app-root',
  imports: [Badge],
  template: `
    <h2>Signals guide <app-badge /></h2>
    <h2>Deferrable views <app-badge /></h2>
  `,
})
export class App {}

Two details to notice:

  1. App lists Badge in its imports. Forget this and the compiler reports "'app-badge' is not a known element".
  2. <app-badge /> uses a self-closing tag, which Angular templates allow for components.

Component state and methods

Fields of the class are available in the template, and so are its methods. Mark members that only the template uses as protected to keep them out of the public API:

angular · try it yourself
import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-like-button',
  template: `
    <button (click)="like()">♥ {{ likes() }}</button>
    <small>{{ label() }}</small>
  `,
})
export class LikeButton {
  protected likes = signal(41);

  protected like() {
    this.likes.update((n) => n + 1);
  }

  protected label() {
    return this.likes() === 1 ? '1 like' : `${this.likes()} likes`;
  }
}

A component is just a class

Strip away the decorator and a component is an ordinary TypeScript class. That makes its logic easy to reason about — and to test. This plain-TS version of the like button behaves exactly like the component's code:

ts · try it yourself
class LikeButtonLogic {
  private likes = 41;

  like(): void {
    this.likes += 1;
  }

  label(): string {
    return this.likes === 1 ? '1 like' : `${this.likes} likes`;
  }
}

const btn = new LikeButtonLogic();
console.log(btn.label());
btn.like();
console.log(btn.label());
41 likes
42 likes

Selectors and naming

Selector form Example Used as
Element (most common) 'app-user-card' <app-user-card />
Attribute '[appToolbar]' <div appToolbar></div>
Class '.panel' <div class="panel"></div>

Element selectors must contain a dash, just like native custom elements, and the prefix (app- by default) avoids clashes with real HTML tags and third-party libraries.

Tip: Keep components small. If a template grows past roughly a screen of HTML, look for a piece you can extract into its own child component.

Test yourself

What must you do before using <app-badge /> inside another standalone component's template?

  1. Add Badge to that component's imports
  2. Add it to index.html
  3. Register it in angular.json
  4. Nothing — all components are global

Which option points to an external HTML file?

  1. template
  2. htmlUrl
  3. templateUrl
  4. selector

Why mark a method used only by the template as protected?

  1. Templates can only call protected methods
  2. It keeps the member out of the component's public API while still allowing template access
  3. It makes the method run faster
  4. It is required for signals