Saturday, August 16, 2025
0 comments

Master Angular 20 : Components - A Beginner’s Guide with Hands-On Examples (Part-1)

 


What is a Component?A component in Angular is a fundamental building block of the application. It represents a reusable piece of the user interface (UI) that combines:
  • HTML template: Defines the view or UI structure.
  • TypeScript class: Handles the logic and data.
  • CSS styles: Defines the component’s appearance.
  • Metadata: Configures how the component behaves (via the @Component decorator).
Each component controls a specific part of the UI, such as a navigation bar, user profile, or form.
Generating a Component with CLIAngular CLI simplifies component creation. To generate a component named User in a components folder, use:
bash
ng g component components/user
This command creates:
  • user.component.ts (TypeScript logic)
  • user.component.html (HTML template)
  • user.component.css (Styles)
  • user.component.spec.ts (Test file)
It also updates the module (or declares the component if standalone: true).
Component Metadata (
@Component
Decorator)
The @Component decorator defines metadata for the component, telling Angular how to process it. Key properties include:
  • selector: The custom HTML tag to use the component (e.g., <app-user>).
  • templateUrl: Path to the component’s HTML template file.
  • styleUrls: Array of paths to CSS files for styling.
  • standalone: If true, the component doesn’t belong to an NgModule (new in Angular 14+).
Example:
typescript
import { Component } from '@angular/core';

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css'],
  standalone: true
})
export class UserComponent {
  // Component logic here
}
  • selector: Use <app-user></app-user> in parent templates to render this component.
  • templateUrl: Points to user.component.html for the UI.
  • styleUrls: Points to user.component.css for styles.
  • standalone: true: Indicates this component is self-contained and doesn’t require an NgModule.

Component StructureA component typically consists of three files:
  1. .ts (TypeScript): Contains the component class, logic, and lifecycle hooks.
  2. .html: Defines the UI template.
  3. .css: Contains styles specific to the component.
Example structure for UserComponent:
src/app/components/user/
├── user.component.ts
├── user.component.html
├── user.component.css

Interpolation {{ }} and Property Binding
  • Interpolation: Displays component data in the template using {{ variable }}.
  • Property Binding: Binds a component property to an HTML element property using [property]="value".
Example:
typescript
// user.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  standalone: true
})
export class UserComponent {
  name = 'John Doe';
}
html
<!-- user.component.html -->
<p>Hello, {{ name }}!</p>
<input [value]="name" />
  • {{ name }} displays the name property’s value.
  • [value]="name" binds the name property to the input’s value attribute.

Event Binding ((event))Event binding listens for user actions (e.g., clicks) and calls component methods using (event)="method()".Example:
typescript
// user.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  standalone: true
})
export class UserComponent {
  message = '';
  onClick() {
    this.message = 'Button clicked!';
  }
}
html
<!-- user.component.html -->
<button (click)="onClick()">Click Me</button>
<p>{{ message }}</p>
  • (click)="onClick()" calls the onClick method when the button is clicked.

Two-Way Data Binding ([(ngModel)])Two-way data binding synchronizes data between the component and the template. It requires the FormsModule.Example:
typescript
// user.component.ts
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  standalone: true,
  imports: [FormsModule] // Import FormsModule for ngModel
})
export class UserComponent {
  username = 'John';
}
html
<!-- user.component.html -->
<input [(ngModel)]="username" />
<p>You typed: {{ username }}</p>
  • [(ngModel)] binds the input value to the username property, updating both on change.
  • FormsModule must be imported for ngModel to work.

Lifecycle HooksLifecycle hooks are methods Angular calls at specific points in a component’s lifecycle. Common hooks include:
  • ngOnInit: Called once after the component is initialized.
  • ngOnDestroy: Called before the component is destroyed.
Example:
typescript
import { Component, OnInit, OnDestroy } from '@angular/core';

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  standalone: true
})
export class UserComponent implements OnInit, OnDestroy {
  ngOnInit() {
    console.log('UserComponent initialized');
  }

  ngOnDestroy() {
    console.log('UserComponent destroyed');
  }
}
  • ngOnInit is ideal for initialization tasks (e.g., fetching data).
  • ngOnDestroy is used for cleanup (e.g., unsubscribing from observables).

Hands-on Project: Create User & Admin ComponentsLet’s create a simple Angular project with two components: UserComponent and AdminComponent. Each will have a form and log lifecycle events.Step 1: Set Up the Project
  1. Install Angular CLI (if not installed):
    bash
    npm install -g @angular/cli
  2. Create a new Angular project:
    bash
    ng new angular-components-demo
    cd angular-components-demo
  3. Generate the components:
    bash
    ng g component components/user
    ng g component components/admin
  4. Configure the app.component.html to include both components:
    html
    <!-- src/app/app.component.html -->
    <app-user></app-user>
    <app-admin></app-admin>
  5. Ensure app.component.ts is standalone (Angular 20 defaults to standalone components):
    typescript
    // src/app/app.component.ts
    import { Component } from '@angular/core';
    import { UserComponent } from './components/user/user.component';
    import { AdminComponent } from './components/admin/admin.component';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      standalone: true,
      imports: [UserComponent, AdminComponent]
    })
    export class AppComponent {}
Step 2: Implement UserComponentThis component will have a form to capture a user’s name and email, with lifecycle logging.
typescript
// src/app/components/user/user.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css'],
  standalone: true,
  imports: [FormsModule]
})
export class UserComponent implements OnInit, OnDestroy {
  user = { name: '', email: '' };

  ngOnInit() {
    console.log('UserComponent: Initialized');
  }

  ngOnDestroy() {
    console.log('UserComponent: Destroyed');
  }

  onSubmit() {
    console.log('User Form Submitted:', this.user);
  }
}
html
<!-- src/app/components/user/user.component.html -->
<h2>User Form</h2>
<form (ngSubmit)="onSubmit()">
  <label>Name: </label>
  <input [(ngModel)]="user.name" name="name" placeholder="Enter name" />
  <br /><br />
  <label>Email: </label>
  <input [(ngModel)]="user.email" name="email" placeholder="Enter email" />
  <br /><br />
  <button type="submit">Submit</button>
</form>
<p>User: {{ user.name }} | Email: {{ user.email }}</p>
css
/* src/app/components/user/user.component.css */
form {
  margin: 20px;
  padding: 20px;
  border: 1px solid #ccc;
}
input {
  padding: 5px;
  margin: 5px;
}
Step 3: Implement AdminComponentThis component will have a form to capture an admin’s role and log lifecycle events.
typescript
// src/app/components/admin/admin.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-admin',
  templateUrl: './admin.component.html',
  styleUrls: ['./admin.component.css'],
  standalone: true,
  imports: [FormsModule]
})
export class AdminComponent implements OnInit, OnDestroy {
  admin = { role: '' };

  ngOnInit() {
    console.log('AdminComponent: Initialized');
  }

  ngOnDestroy() {
    console.log('AdminComponent: Destroyed');
  }

  onSubmit() {
    console.log('Admin Form Submitted:', this.admin);
  }
}
html
<!-- src/app/components/admin/admin.component.html -->
<h2>Admin Form</h2>
<form (ngSubmit)="onSubmit()">
  <label>Role: </label>
  <input [(ngModel)]="admin.role" name="role" placeholder="Enter role" />
  <br /><br />
  <button type="submit">Submit</button>
</form>
<p>Admin Role: {{ admin.role }}</p>
css
/* src/app/components/admin/admin.component.css */
form {
  margin: 20px;
  padding: 20px;
  border: 1px solid #007bff;
}
input {
  padding: 5px;
  margin: 5px;
}
Step 4: Run the Application
  1. Start the Angular development server:
    bash
    ng serve
  2. Open your browser and navigate to http://localhost:4200.
  3. You should see:
    • A User Form with fields for name and email.
    • An Admin Form with a field for role.
    • Open the browser’s console (F12) to see lifecycle logs (ngOnInit when components load, ngOnDestroy if you navigate away or destroy the component).
  4. Test the forms:
    • Enter data in the User and Admin forms.
    • Submit the forms to see the console logs with form data.
Step 5: Verify Lifecycle LogsTo test ngOnDestroy, you can conditionally show/hide components using *ngIf:
html
<!-- src/app/app.component.html -->
<button (click)="showUser = !showUser">Toggle User Component</button>
<button (click)="showAdmin = !showAdmin">Toggle Admin Component</button>
<app-user *ngIf="showUser"></app-user>
<app-admin *ngIf="showAdmin"></app-admin>
typescript
// src/app/app.component.ts
import { Component } from '@angular/core';
import { UserComponent } from './components/user/user.component';
import { AdminComponent } from './components/admin/admin.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  standalone: true,
  imports: [UserComponent, AdminComponent]
})
export class AppComponent {
  showUser = true;
  showAdmin = true;
}
  • Click the toggle buttons to add/remove components.
  • Check the console for ngOnInit (when added) and ngOnDestroy (when removed).

Summary
  • Components: Building blocks of Angular apps, combining logic, template, and styles.
  • CLI: Use ng g component to generate components.
  • Metadata: @Component defines selector, templateUrl, styleUrls, and standalone.
  • Data Binding:
    • Interpolation ({{ }}): Display data.
    • Property Binding ([]): Bind data to properties.
    • Event Binding (()): Handle user events.
    • Two-Way Binding ([(ngModel)]): Sync data with FormsModule.
  • Lifecycle Hooks: Use ngOnInit for initialization and ngOnDestroy for cleanup.
  • Project: You created User and Admin components with forms and lifecycle logging.

0 comments:

Featured Post

Master Angular 20 Basics: A Complete Beginner’s Guide with Examples and Best Practices

Welcome to the complete Angular 20 learning roadmap ! This series takes you step by step from basics to intermediate concepts , with hands...

Subscribe

 
Toggle Footer
Top