Components

Angular · Essentials · 12 min

Components are the building blocks of every Angular UI.

An Angular component is a TypeScript class decorated with @Component. The decorator's metadata tells Angular how to render it:

  • selector — the custom HTML tag that places the component, e.g. 'app-user-card' used as <app-user-card />. Prefix selectors (app-) to avoid clashing with real HTML elements.
  • template (inline) or templateUrl (separate .html file) — the markup.
  • styles or styleUrl — CSS that is encapsulated: Angular rewrites selectors so they only match this component's elements.
  • imports — the other components, directives and pipes this template uses. If you use <app-avatar> without importing Avatar, the build fails with an "unknown element" error.

Class fields and methods are available to the template. Fields used in templates are usually protected (visible to the template but not part of the public API) and often signals, which you read by calling them: {{ name() }}.

@Component({ selector: 'app-hello', template: `<h1>Hello {{ name() }}</h1>` })
export class Hello { protected name = signal('Ada'); }

Components form a tree starting at the root component bootstrapped in main.ts. Keep components small and focused: a page component composes smaller presentational components, each with a clear set of inputs and outputs.

Example

import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-avatar',
  template: `<img [src]="url()" alt="avatar" />`,
  styles: `img { width: 48px; border-radius: 50%; }`,
})
export class Avatar {
  protected url = signal('https://example.com/ada.png');
}

@Component({
  selector: 'app-user-card',
  imports: [Avatar],                      // everything the template uses
  template: `
    <app-avatar />
    <h2>{{ name() }}</h2>
    <p>Member since {{ year }}</p>
  `,
  styles: `h2 { margin: 0; }`,            // scoped to this component
})
export class UserCard {
  protected name = signal('Ada Lovelace');
  protected year = 2024;
}

Remember

  • @Component = selector + template + styles + imports on a TypeScript class
  • List every component, directive and pipe the template uses in imports
  • Styles are encapsulated per component by default

Watch out for

  • Forgetting to add a child component to imports, causing "is not a known element" build errors.

Check yourself

  1. A template uses <app-chart> but the build reports "'app-chart' is not a known element". What is the most likely fix?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: angular.dev/guide/components