Learn Angular · 2/14

Components: The Building Blocks of UI

8 min read

Welcome back to the FreeCodeCamp guide.

In the vast ecosystem of web development, we often strive for modularity—the ability to break complex systems into manageable, reusable pieces. In Angular, this philosophy is encapsulated in the Component.

If you were building a LEGO® castle, a component would not be the castle itself; it would be the individual brick, the window frame, or the drawbridge mechanism. Together, they form the masterpiece.

Today, we will dissect the architecture of Angular components, master the Command Line Interface (CLI) to generate them, control their lifespan with lifecycle hooks, and enable them to communicate with one another.


1. Anatomy of a Component: Template, Class, and Styles 🏗️

The Definition and The Problem

The Problem: In early web development, HTML, JavaScript, and CSS were often scattered across different directories or spaghetti-coded into single massive files. This made maintenance a nightmare. If a button broke, did you fix the HTML, the global script, or the stylesheet?

The Solution: The Angular Component. A component encapsulates a specific piece of the user interface (UI) and the logic that drives it into a single cohesive unit. It enforces a strict separation of concerns while keeping related code physically close.

The Implementation

Technically, a component is a TypeScript class decorated with @Component. This decorator provides metadata that tells Angular how to instantiate, render, and style the component.

Every Angular component consists of three pillars:

  1. The Template (HTML): The structure and layout (the skeleton).
  2. The Class (TypeScript): The state and behavior (the brain).
  3. The Styles (CSS/SCSS): The look and feel (the skin).

Let us examine a modern, standalone component structure.

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

@Component({
  selector: 'app-user-card',
  standalone: true, // Modern Angular standard (v14+)
  template: `
    <div class="card">
      <h2>{{ userName }}</h2>
      <button (click)="greetUser()">Say Hello</button>
    </div>
  `,
  styles: [`
    .card {
      border: 1px solid #ccc;
      padding: 1rem;
      border-radius: 8px;
    }
    h2 { color: #2c3e50; }
  `]
})
export class UserCardComponent {
  // 1. Property (State)
  userName: string = 'Ada Lovelace';

  // 2. Method (Behavior)
  greetUser(): void {
    console.log(`Hello, ${this.userName}!`);
  }
}

Deep Dive: The Metadata

  • selector: This defines the custom HTML tag used to insert this component into other templates. Using 'app-user-card' allows you to use <app-user-card></app-user-card> anywhere in your application.
  • template vs templateUrl: For small components, inline HTML (backticks) is acceptable. For complex layouts, we use templateUrl: './user-card.component.html' to link an external file.
  • styles vs styleUrls: Similar to templates, styles can be inline or external.
  • standalone: true: This is the modern standard. It means the component does not need to be declared in an NgModule. It manages its own dependencies via the imports array.

Did You Know? 💡
The concept of separating UI into components isn't unique to Angular. It aligns with the W3C Web Components standard. However, Angular adds a layer of "Dependency Injection" and "Change Detection" that makes these components reactive and intelligent, far surpassing standard HTML elements.


2. Generating Components with the CLI ⚙️

The Definition and The Problem

The Problem: Writing the boilerplate code above manually (creating files, importing Component, setting up metadata, linking styles) is repetitive, boring, and prone to human error. A missing comma or a typo in a filename can stop an application from compiling.

The Solution: The Angular CLI (Command Line Interface). It automates the generation process, ensuring files are named correctly, linked appropriately, and adhere to the official Angular Style Guide.

The Command

To generate a new component, open your terminal and run:

bash
ng generate component components/user-profile

Or the shorthand notation used frequently in the industry:

bash
ng g c components/user-profile

What happens under the hood?

The CLI performs the following actions:

  1. Creates a directory: src/app/components/user-profile/
  2. Generates four files:
    • user-profile.component.ts (The logic)
    • user-profile.component.html (The template)
    • user-profile.component.css (The styles)
    • user-profile.component.spec.ts (The unit test file)
  3. Updates the usage context (if not standalone, it registers it in app.module.ts).

Industry Standards

In professional environments, we often add flags to control the output.

  • Skip Tests: If you are prototyping.
    ng g c user-profile --skip-tests
  • Inline Styles: If the component is very small (like a button).
    ng g c user-profile --inline-style
  • Prefixing:
    Angular applies a prefix (default app-) to prevent collisions with standard HTML tags. You cannot name a selector div, but you can name it app-div.

Imagination Check 🧠
Imagine if you had to build a car by forging every screw by hand every time you needed one. That is coding without the CLI. The CLI is your factory assembly line; you press a button, and the perfect part arrives, ready to be installed.


3. Essential Lifecycle Hooks: ngOnInit and ngOnDestroy 🔄

The Definition and The Problem

The Problem: A component is not a static object. It is born (instantiated), it lives (renders data), and it dies (is removed from the DOM). Sometimes we need to fetch data immediately when the component loads, or clean up a timer when the user navigates away. Putting this logic in the constructor is a common mistake.

The Solution: Lifecycle Hooks. These are specific methods exposed by Angular interfaces that allow us to tap into key moments in a component's existence.

ngOnInit: Initialization

The constructor is a TypeScript feature used strictly for Dependency Injection. The ngOnInit hook is an Angular feature used for initialization logic (e.g., calling an API).

Why separate them? The Input bindings (data passed from parents) are not available in the constructor. They are only guaranteed to be available in ngOnInit.

ngOnDestroy: Cleanup

When a component is removed from the DOM (e.g., the user navigates to a different page), ngOnDestroy is called. This is critical for preventing "Memory Leaks."

The Zombie Component 🧟
If you start a timer or subscribe to a data stream in a component but fail to stop it in ngOnDestroy, that process continues running in the background even after the component "dies." It becomes a Zombie, eating up your browser's RAM and CPU.

Practical Implementation

typescript
import { Component, OnInit, OnDestroy } from '@angular/core';

@Component({
  selector: 'app-timer',
  standalone: true,
  template: `<p>Time elapsed: {{ seconds }}</p>`
})
export class TimerComponent implements OnInit, OnDestroy {
  seconds = 0;
  intervalId: any;

  constructor() {
    // strict: avoid logic here. 
    console.log('1. Constructor: Component creates. Inputs not ready.');
  }

  ngOnInit(): void {
    console.log('2. OnInit: Component initialized. Inputs ready.');
    // Start a timer
    this.intervalId = setInterval(() => {
      this.seconds++;
      console.log('Timer ticking...');
    }, 1000);
  }

  ngOnDestroy(): void {
    console.log('3. OnDestroy: Component is being removed.');
    // Stop the timer to prevent memory leaks
    if (this.intervalId) {
      clearInterval(this.intervalId);
    }
  }
}

4. Component Communication: Passing Data with @Input and @Output 📡

The Definition and The Problem

The Problem: By default, Angular components are isolated silos. A "Product List" component doesn't know about the "Product Item" component inside it, and the "Product Item" cannot tell the "List" that it has been clicked. They need a protocol to speak.

The Solution: The @Input() and @Output() decorators.

  • @Input(): Data flows Down (Parent →\rightarrow Child).
  • @Output(): Events flow Up (Child →\rightarrow Parent).

The Implementation

Let us visualize a ParentComponent (The Dashboard) passing a user's name to a ChildComponent (The Badge). The Child then tells the Parent when the user logs out.

1. The Child Component (user-badge.component.ts)

The child receives the name and emits an event.

typescript
import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-user-badge',
  standalone: true,
  template: `
    <div class="badge">
      <!-- Display Input data -->
      <span>User: {{ name }}</span>
      
      <!-- Trigger Output event -->
      <button (click)="onLogout()">Logout</button>
    </div>
  `
})
export class UserBadgeComponent {
  // @Input: Expecting data from the parent
  @Input() name: string = '';

  // @Output: Broadcasting an event to the parent
  @Output() logoutEvent = new EventEmitter<void>();

  onLogout() {
    // Emit the event up to the parent
    this.logoutEvent.emit();
  }
}

2. The Parent Component (dashboard.component.ts)

The parent binds to the input property ([]) and listens to the output event (()).

typescript
import { Component } from '@angular/core';
import { UserBadgeComponent } from './user-badge.component';

@Component({
  selector: 'app-dashboard',
  standalone: true,
  imports: [UserBadgeComponent], // Import child to use it
  template: `
    <h1>Dashboard</h1>
    
    <!-- 
       [name]="currentUser": Property Binding (Down)
       (logoutEvent)="handleLogout()": Event Binding (Up)
    -->
    <app-user-badge 
      [name]="currentUser" 
      (logoutEvent)="handleLogout()">
    </app-user-badge>
  `
})
export class DashboardComponent {
  currentUser = 'Maverick';

  handleLogout() {
    alert('User has logged out!');
    this.currentUser = 'Guest';
  }
}

Industry Note: The Modern Shift

While @Input and @Output are standard, Angular v17.1+ introduced Signal Inputs.
Instead of @Input() name: string, you might see name = input<string>(). This provides better performance and reactivity. However, understanding the decorator pattern shown above is mandatory for maintaining existing enterprise codebases.


Conclusion

We have journeyed from the atomic structure of a component to the complex interactions between them. You now possess the knowledge to:

  1. Scaffold components using the CLI.
  2. Structure your logic, view, and styles.
  3. Manage the lifecycle of your application state.
  4. Orchestrate communication between different parts of your UI.

As you practice, remember: A great UI is not just about looking good; it is about well-organized, isolated, and communicative components working in harmony.

References & Further Reading 📚

Challenge

Task

You are building a user management dashboard. Your task is to create two interconnected, standalone Angular components: UserCardComponent and UserListComponent.

UserCardComponent (Child) Requirements:

  1. Component Metadata:

    • Make it a standalone component.
    • Define a selector of app-user-card.
    • Use an inline template and inline styles.
  2. Data Input:

    • Create an @Input() property named user that accepts an object with the shape { name: string, email: string, status: 'active' | 'inactive' }.
  3. Event Output:

    • Create an @Output() property named onDelete that is an EventEmitter which emits the user's email (string) when triggered.
  4. Template and Style:

    • The template must display the user's name, email, and status.
    • Include a <button> with the text "Remove". When this button is clicked, it must trigger the onDelete event emitter, passing the user's email.
    • Add a simple border and padding to the card for styling.
  5. Lifecycle Hooks:

    • Implement the OnInit lifecycle hook. Inside ngOnInit, you don't need to perform a real action, but the method must be correctly declared as if it were to be used for initialization logic.
    • Implement the OnDestroy lifecycle hook. Similarly, declare the ngOnDestroy method correctly for potential cleanup logic.

UserListComponent (Parent) Requirements:

  1. Component Metadata:

    • Make it a standalone component.
    • Define a selector of app-user-list.
    • Import the UserCardComponent to make it usable within the template.
  2. State Management:

    • In the component class, create a public property users and initialize it with an array of at least three user objects, each matching the shape defined for the user input.
  3. Template Logic:

    • Use the modern @for block to iterate over the users array.
    • For each user in the array, render an <app-user-card> component.
    • Use property binding to pass the user object from the iteration to the user input of the UserCardComponent.
    • Use event binding to listen for the onDelete event from the UserCardComponent and call a handler method in the UserListComponent.
  4. Class Logic:

    • Create a public method handleUserDelete(email: string). This method should update the users array by removing the user whose email matches the one received from the event.

Expected result

UserCardComponent

Your UserCardComponent class should be decorated with @Component and implement OnInit and OnDestroy. The decorator's metadata must specify selector, standalone: true, an inline template, and inline styles. The class must contain an @Input() property named user and an @Output() property named onDelete which is an instance of EventEmitter<string>. The template should display properties from the user object and include a button with a (click) event that calls a method to emit the user's email.

typescript
import { Component, Input, Output, EventEmitter, OnInit, OnDestroy } from '@angular/core';

interface User {
  name: string;
  email: string;
  status: 'active' | 'inactive';
}

@Component({
  selector: 'app-user-card',
  standalone: true,
  template: `
    <div class="card">
      <h4>{{ user.name }}</h4>
      <p>Email: {{ user.email }}</p>
      <p>Status: {{ user.status }}</p>
      <button (click)="deleteUser()">Remove</button>
    </div>
  `,
  styles: [`
    .card { 
      border: 1px solid #ccc; 
      padding: 1rem; 
      margin: 0.5rem; 
      border-radius: 8px; 
    }
  `]
})
export class UserCardComponent implements OnInit, OnDestroy {
  @Input() user!: User;
  @Output() onDelete = new EventEmitter<string>();

  ngOnInit(): void {
    console.log('UserCardComponent initialized for:', this.user.name);
  }

  ngOnDestroy(): void {
    console.log('UserCardComponent destroyed for:', this.user.name);
  }

  deleteUser(): void {
    this.onDelete.emit(this.user.email);
  }
}

UserListComponent

Your UserListComponent should be a standalone component that imports UserCardComponent. Its template must use an @for block to iterate over a local users array. For each user, it should render an <app-user-card>, binding the user object to the [user] input and the handleUserDelete($event) method to the (onDelete) output. The handleUserDelete method itself should correctly filter the users array to remove the user with the matching email.

typescript
import { Component } from '@angular/core';
// Assuming UserCardComponent and User interface are in the same scope/file.

@Component({
  selector: 'app-user-list',
  standalone: true,
  imports: [UserCardComponent],
  template: `
    <div>
      <h2>User List</h2>
      @for (user of users; track user.email) {
        <app-user-card 
          [user]="user" 
          (onDelete)="handleUserDelete($event)">
        </app-user-card>
      }
    </div>
  `
})
export class UserListComponent {
  users: User[] = [
    { name: 'Alice Johnson', email: '[email protected]', status: 'active' },
    { name: 'Bob Smith', email: '[email protected]', status: 'inactive' },
    { name: 'Charlie Brown', email: '[email protected]', status: 'active' }
  ];

  handleUserDelete(email: string): void {
    this.users = this.users.filter(user => user.email !== email);
  }
}
typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.