Back to course

Deep Dive into Components

The Complete Angular Developer: From Zero to Hero

8. Deep Dive into Components

Components are the fundamental building blocks of Angular UIs. A component controls a section of the screen, or a view, and handles user interactions for that view.

The Component Structure

Every component consists of three parts:

  1. The Class (.ts): Contains the data (properties) and logic (methods).
  2. The Template (.html): Defines the component's UI structure.
  3. The Metadata (@Component): Configures the component, linking the class to the template and selector.

Creating a New Component via CLI

bash ng generate component user-profile // or shorthand ng g c user-profile

This command generates four files:

  • user-profile.component.ts
  • user-profile.component.html
  • user-profile.component.css
  • user-profile.component.spec.ts (for testing)

It also automatically updates the nearest NgModule (AppModule) by adding UserProfileComponent to the declarations array.

Component Metadata Example

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

@Component({ selector: 'app-user-profile', // How the component is used in HTML templateUrl: './user-profile.component.html', // Link to the view styleUrls: ['./user-profile.component.css'] // Link to component-specific styles }) export class UserProfileComponent { userName: string = 'Alex Johnson'; isActive: boolean = true;

toggleStatus(): void { this.isActive = !this.isActive; } }

To use this component, you simply place its selector tag in another component's template:

html

Application Dashboard