Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 4: Components and Templates

Angular applications are built out of components. If you imagine an Angular app as a house, components are the rooms: each with a specific purpose, walls that separate it from the rest, and an entrance that lets you interact with it. Together, they form the whole structure.

This chapter will walk you through everything you need to know about components — how they are created, structured, and how they interact with templates. By the end, you’ll have built a solid foundation for building user interfaces in Angular.


4.1 What is a Component?

A component is the basic building block of Angular applications. It controls a portion of the screen — called a view. Every Angular component has three main parts:

  1. Class (TypeScript) – defines the behavior and data.
  2. Template (HTML) – defines the UI layout.
  3. Metadata (Decorator) – tells Angular how to connect the class and the template.

At runtime, Angular takes your component class, combines it with the template, and renders it into the browser DOM.


4.2 Creating a Component

The easiest way to create a new component is by using the Angular CLI:

ng generate component hello-world
# or shorthand:
ng g c hello-world

This command will create four files in a new folder hello-world/:

hello-world/
  hello-world.component.ts      # Component class + metadata
  hello-world.component.html    # Template
  hello-world.component.css     # Styles
  hello-world.component.spec.ts # Unit tests

Let’s open hello-world.component.ts:

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

@Component({
  selector: 'app-hello-world',
  templateUrl: './hello-world.component.html',
  styleUrls: ['./hello-world.component.css']
})
export class HelloWorldComponent {
  message: string = 'Hello, Angular!';
}
  • @Component is a decorator that marks the class as an Angular component.
  • selector is the HTML tag you use to render the component.
  • templateUrl points to the component’s HTML file.
  • styleUrls points to the CSS file.

In hello-world.component.html, you might write:

<h1>{{ message }}</h1>

And finally, in app.component.html, include your component:

<app-hello-world></app-hello-world>

4.3 Template Syntax

Angular templates are more than static HTML. They include a set of powerful features:


4.3.1 Interpolation

Use {{ ... }} to display component data.

TypeScript (Component):

export class HelloWorldComponent {
  message: string = 'Angular is awesome!';
}

Template:

<p>{{ message }}</p>

4.3.2 Property Binding

Bind element properties to component values using [ ].

TypeScript (Component):

export class ProfileComponent {
  profilePictureUrl: string = 'https://example.com/avatar.png';
}

Template:

<img [src]="profilePictureUrl" alt="User profile picture">

4.3.3 Event Binding

Bind DOM events to component methods using ( ).

TypeScript (Component):

export class ButtonComponent {
  sayHello() {
    alert('Hello from Angular!');
  }
}

Template:

<button (click)="sayHello()">Click me</button>

4.3.4 Two-Way Binding

Use [(ngModel)] for two-way data binding (requires FormsModule).

TypeScript (Component):

export class UserFormComponent {
  username: string = '';
}

Template:

<input [(ngModel)]="username" placeholder="Enter your name">
<p>You typed: {{ username }}</p>

4.4 Lifecycle Hooks

Angular components have a lifecycle — from creation to destruction. You can hook into this lifecycle using special methods:

  • ngOnInit() – runs once after component initialization.
  • ngOnChanges() – runs when input properties change.
  • ngOnDestroy() – runs just before the component is removed.

Example:

export class HelloWorldComponent implements OnInit, OnDestroy {
  ngOnInit() {
    console.log('Component initialized');
  }

  ngOnDestroy() {
    console.log('Component destroyed');
  }
}

4.5 Component Communication

Components rarely live in isolation. They need to talk to each other.

4.5.1 Input Properties

Pass data from a parent component into a child component:

export class ChildComponent {
  @Input() title!: string;
}

Template usage:

<app-child [title]="'Dashboard'"></app-child>

4.5.2 Output Events

Send data from a child component to its parent:

export class ChildComponent {
  @Output() clicked = new EventEmitter<string>();

  handleClick() {
    this.clicked.emit('Child button clicked!');
  }
}

Template:

<button (click)="handleClick()">Click me</button>

Parent usage:

<app-child (clicked)="onChildClicked($event)"></app-child>

4.6 Styling Components

Angular components have their own style files. By default, styles are scoped to the component (thanks to View Encapsulation).

h1 {
  color: blue;
}

This CSS applies only to the component’s template, not globally. You can override this behavior by changing encapsulation in the decorator.


4.7 Best Practices

  • Keep components small and focused – one responsibility per component.
  • Use smart (container) and dumb (presentational) components.
  • Avoid deeply nested components; favor flat hierarchies.
  • Name selectors consistently (e.g., always prefix with app-).

4.8 Summary

In this chapter, you learned that:

  • A component is the fundamental building block of Angular apps.
  • Components consist of a class, template, and metadata.
  • Templates use Angular’s powerful binding syntax.
  • Lifecycle hooks let you react to changes over time.
  • Components communicate via @Input and @Output.