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:
- The Class (.ts): Contains the data (properties) and logic (methods).
- The Template (.html): Defines the component's UI structure.
- 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.tsuser-profile.component.htmluser-profile.component.cssuser-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