Skip to main content

Posts

Showing posts with the label Angular Roadmap

Introduction to NgRx (State Management) in Angular

๐Ÿš€ What is NgRx? NgRx is a state management library for Angular applications. It is based on Redux principles and provides a way to manage application state in a predictable manner. State represents the data of your application at any given point in time. ๐Ÿ“ฆ Why Use NgRx? Benefit Description Predictable State Ensures the state is predictable and consistent. Centralized State Centralizes state management, making it easier to manage and debug. Time Travel Debugging Allows you to travel back and forth through state changes. Scalable Suitable for large applications with complex state management needs. ๐Ÿ”ฅ Basic Example Suppose you want to manage a list of products using NgRx: 1. Install NgRx Packages ng add @ngrx/store ng add @ngrx/effects ng add @ngrx/entity ng add @ngrx/store-devtools 2. Define State and Actions Create pro...

Sharing Data with Subjects & BehaviorSubjects (RxJS) In angular

๐Ÿš€ What are Subjects & BehaviorSubjects? Subjects are special types of observables in RxJS that allow values to be multicasted to multiple observers. BehaviorSubjects are a type of Subject that also holds the current value and emits it to new subscribers. ๐Ÿ“ฆ Why Use Subjects & BehaviorSubjects? Benefit Description Multicasting Allows multiple subscribers to receive the same values. State Management BehaviorSubjects hold the current value, useful for state management. Flexibility Subjects can be used for various patterns like event handling, data sharing, etc. ๐Ÿ”ฅ Basic Example Suppose you want to share data between components using a BehaviorSubject: 1. Create a Service with a BehaviorSubject ng generate service data This generates data.service.ts : import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs...

Dependency Injection in Angular

๐Ÿš€ What is Dependency Injection? Dependency Injection (DI) is a design pattern . It allows a class to receive its dependencies (services, objects) from the outside , rather than creating them itself. Angular has a powerful built-in DI system that manages and injects dependencies automatically. ๐Ÿ“ฆ Why Use Dependency Injection? Benefit Description Loose Coupling Classes are not tightly tied to their dependencies. Reusability Easier to reuse code and services. Testability Easier to mock dependencies for unit testing. Maintainability Cleaner, more modular code. ๐Ÿ”ฅ Basic Example Suppose you have a service that provides user data: 1. Create a Service ng generate service user This generates user.service.ts : import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' // Angular will automati...

Creating and using services in Angular

๐Ÿš€ What are Services? Services are classes that provide reusable functionality across your Angular application. They help encapsulate business logic and data access in a centralized way. ๐Ÿ“ 1. Create a Service Suppose you want to create a DataService to manage data operations. Generate the service: ng generate service data Inside data.service.ts : import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class DataService { private data: any[] = []; constructor() { } getData() { return this.data; } addData(item: any) { this.data.push(item); } } ๐Ÿ“„ 2. Inject and Use the Service in a Component In app.component.ts : import { Component, OnInit } from '@angular/core'; import { DataService } from './data.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppC...

Route guards in Angular

๐Ÿš€ What are Route Guards? Route Guards are interfaces that allow you to control access to routes in your Angular application. They help protect routes by checking conditions before navigating to them. ๐Ÿ“ 1. Create an AuthGuard Suppose you want to create an AuthGuard to protect certain routes. Generate the guard: ng generate guard auth Inside auth.guard.ts : import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router'; import { AuthService } from './auth.service'; @Injectable({ providedIn: 'root' }) export class AuthGuard implements CanActivate { constructor(private authService: AuthService, private router: Router) {} canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { const isLoggedIn = this.authService.isLoggedIn(); if (!isLoggedIn) { this.router.navigate(['/login']); } ...

Lazy Loading in Angular

๐Ÿš€ What is Lazy Loading? Lazy Loading means loading modules only when needed , not when the app starts. It helps improve the initial load time of your Angular app. ๐Ÿ“ 1. Create a Feature Module Suppose you want to lazy-load a ProductsModule . Generate a module and a component: ng generate module products --route products --module app.module ng generate component products/products-list or manually: ng generate module products ng generate component products/products-list Inside products-routing.module.ts : import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { ProductsListComponent } from './products-list/products-list.component'; const routes: Routes = [ { path: '', component: ProductsListComponent } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class ProductsRoutingModule { } Inside products.module.ts : import { NgModu...

Route Parameters in Angular

How to define a route with a parameter: In your app-routing.module.ts : const routes: Routes = [ { path: 'product/:id', component: ProductComponent } ]; :id is a route parameter (dynamic value). Accessing the Route Parameter in the Component In product.component.ts : import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-product', templateUrl: './product.component.html' }) export class ProductComponent { productId!: string; constructor(private route: ActivatedRoute) {} ngOnInit() { this.productId = this.route.snapshot.paramMap.get('id')!; // OR you can subscribe to changes: this.route.paramMap.subscribe(params => { this.productId = params.get('id')!; }); } } Navigating to a Route with Parameters In your template: <a [routerLink]="['/product', 42]">View Product 42</a> or programmatically: this.router.navigate(['/pr...

Install Angular Router (already included if you use Angular CLI)

If you generated your project with: ng new my-app --routing then Angular Router is already set up. If not, you just need to manually configure it — no extra installation required! ๐Ÿ— 2. Create Components You need components to route to. Example: ng generate component home ng generate component about This creates HomeComponent and AboutComponent . ๐Ÿ“œ 3. Define Routes Edit your app-routing.module.ts (or create it if missing): import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { AboutComponent } from './about/about.component'; const routes: Routes = [ { path: '', component: HomeComponent }, { path: 'about', component: AboutComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } ๐Ÿ›  4. Import Router Module in AppModule Ensu...

Reactive Forms & Form Validation

Reactive Forms in Angular Reactive Forms in Angular are model-driven , giving you programmatic control over form logic, structure, and validation entirely from the component class. They're great for complex, dynamic forms and large applications. ๐Ÿ”ง Setup Import ReactiveFormsModule in AppModule : import { ReactiveFormsModule } from '@angular/forms'; @NgModule({ imports: [ReactiveFormsModule] }) export class AppModule { } ๐Ÿง  Example: Reactive Form with Validation ๐Ÿ“„ Component Class ( app.component.ts ) import { Component } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent { userForm: FormGroup; constructor(private fb: FormBuilder) { this.userForm = this.fb.group({ name: ['', [Validators.required]], email: ['', [Validators.required, Validators....

Template driven form

Template-Driven Forms in Angular Template-Driven Forms in Angular provide a simple, declarative way to build forms using Angular directives in the HTML template. They're perfect for basic forms , quick prototypes, or when you want to avoid a lot of TypeScript code. ✅ Key Characteristics Defined in HTML using directives like ngModel , ngForm , ngSubmit Minimal TypeScript logic Powered by FormsModule ๐Ÿ“ฆ Prerequisite Import FormsModule in your AppModule . import { FormsModule } from '@angular/forms'; @NgModule({ imports: [FormsModule] }) export class AppModule { } ๐Ÿงฑ Basic Example ๐Ÿ“„ Template ( app.component.html ) <form #userForm="ngForm" (ngSubmit)="onSubmit(userForm)"> <label>Name: <input type="text" name="name" ngModel required /> </label> <br /> <label>Email: <input type="email" name="email" ngModel required /> </l...

Two-way Data Binding (ngModel)

Two-Way Data Binding in Angular Two-way data binding in Angular is a key concept that allows your UI (view) and your component (model) to stay in sync . It means when the user updates the input, the model gets updated automatically, and vice versa. ๐Ÿ” What is Two-Way Data Binding? Two-way data binding connects a form input element to a component variable both ways : Component → Template (displaying the value) Template → Component (updating the value) ✅ Syntax <input [(ngModel)]="username" /> The [(ngModel)] is shorthand for combining: <input [ngModel]="username" (ngModelChange)="username = $event" /> ๐Ÿ“ฆ Prerequisite You must import FormsModule in your module to use ngModel . import { FormsModule } from '@angular/forms'; @NgModule({ imports: [ FormsModule ] }) export class AppModule { } ✏️ Example Component (app.component.ts) export class AppComponent { username: string = 'AngularD...

Creating Custom Pipes

Custom Pipes in Angular Let's look at how to create custom pipes in Angular — a powerful way to transform data your way when built-in pipes don't cut it. ๐Ÿ”ง When to Create a Custom Pipe? Use a custom pipe when: You want reusable transformations. Built-in pipes don't cover your use case. You want clean templates (instead of complex method calls). ✅ Steps to Create a Custom Pipe 1. Generate a Pipe Use Angular CLI: ng generate pipe myCustom This creates two files: my-custom.pipe.ts my-custom.pipe.spec.ts (for testing) 2. Basic Pipe Example: Reverse a String import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'reverse' }) export class ReversePipe implements PipeTransform { transform(value: string): string { return value.split('').reverse().join(''); } } 3. Use in Template <p>{{ 'angular' | reverse }}</p> <!-- ralu gna --> 4. Using Pipe wi...

Built-in Pipes (uppercase, date, currency)

Built-in Pipes in Angular Let's dive into Built-in Pipes in Angular — a super handy way to format data directly in your templates. Pipes transform your data's display without changing the actual value. ๐Ÿ›  What is a Pipe? A Pipe takes in data as input and transforms it to a desired format. You use pipes with the | (pipe) character in templates. ✅ Common Built-in Pipes Pipe Description Example uppercase Transforms text to all uppercase 'hello' | uppercase → HELLO lowercase Transforms text to all lowercase 'HELLO' | lowercase → hello titlecase Capitalizes first letter of each word 'angular pipe' | titlecase → Angular Pipe date Formats a date today | date:'fullDate' currency Formats number as currency 123.45 | currency:'EUR' → €123...

Custom Directives

Custom Directives in Angular Let's explore Custom Directives in Angular — one of the most powerful features when you want to encapsulate and reuse behavior across components! ๐Ÿงฑ What is a Custom Directive? A custom directive is a class with the @Directive() decorator that allows you to attach custom behavior to elements in the DOM. ✨ Types of Custom Directives Attribute Directive – changes appearance/behavior of elements ( highlight , auto-focus , etc.) Structural Directive – changes the DOM layout ( *ngIf , *ngFor , etc.) ๐Ÿ› ️ Create a Custom Attribute Directive Example Let's create a directive that highlights text when hovered. Step 1: Generate Directive ng generate directive highlight Step 2: Modify the Directive Code // highlight.directive.ts import { Directive, ElementRef, HostListener, Renderer2 } from '@angular/core'; @Directive({ selector: '[appHighlight]' }) export class HighlightDirective { constructor(private ...

Attribute Directives (ngClass, ngStyle)

Angular Attribute Directives: ngClass and ngStyle Unlike structural directives (which add/remove elements), attribute directives change the appearance or behavior of an element by modifying its attributes. ๐ŸŽจ 1. ngClass – Apply CSS Classes Dynamically ✅ Basic Usage: <p [ngClass]="'highlight'">This is highlighted.</p> ✅ Conditional Class: <p [ngClass]="{ 'active': isActive, 'error': hasError }"> Status Message </p> ✅ Multiple Classes Based on Array: <p [ngClass]="['base-class', dynamicClass]">Styled text</p> ๐Ÿ–Œ️ 2. ngStyle – Apply Inline Styles Dynamically ✅ Basic Usage: <p [ngStyle]="{ 'color': 'blue', 'font-weight': 'bold' }"> Styled inline text </p> ✅ Dynamic Style: <p [ngStyle]="{ 'background-color': isError ? 'red' : 'green' }"> Conditional Background </p...

Structural Directives (ngIf, ngFor, ngSwitch)

Angular Structural Directives Guide Structural Directives in Angular are used to alter the DOM layout by adding or removing elements. The most common ones are *ngIf , *ngFor , and *ngSwitch . ✅ 1. *ngIf – Conditional Rendering Used to show or hide an element based on a condition. <p *ngIf="isLoggedIn">Welcome, User!</p> <p *ngIf="!isLoggedIn">Please log in.</p> Optional else clause: <ng-container *ngIf="isLoggedIn; else loginPrompt"> <p>Welcome back!</p> </ng-container> <ng-template #loginPrompt> <p>Please sign in.</p> </ng-template> ๐Ÿ” 2. *ngFor – Iterating Over Lists Used to repeat an element for each item in a list. <ul> <li *ngFor="let item of items; let i = index"> {{ i + 1 }}. {{ item }} </li> </ul> You can also use other local variables like: index first last even odd <div *ngFor=...

Component Communication (@Input(), @Output())

๐Ÿ”น @Input() – Passing Data from Parent to Child Use @Input() when the parent component needs to send data to its child . ✅ Example: parent.component.html <app-child [message]="parentMessage"></app-child> parent.component.ts export class ParentComponent { parentMessage = 'Hello from Parent!'; } child.component.ts import { Component, Input } from '@angular/core'; @Component({ selector: 'app-child', template: `<p>{{ message }}</p>` }) export class ChildComponent { @Input() message: string = ''; } ๐Ÿ”ธ @Output() – Sending Data from Child to Parent Use @Output() when the child component needs to emit an event back to the parent. ✅ Example: child.component.ts import { Component, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-child', template: `<button (click)="sendMessage()">Send Message</button>` }) export class ChildCompo...

Template Syntax in Angular

Template syntax is how Angular binds data and adds logic to your HTML. Let’s break down the essentials: interpolation ( {{ }} ), and structural directives like *ngIf and *ngFor . ๐Ÿงฉ Interpolation – {{ }} Interpolation is used to display data from your component class in the template. ✅ Example: <p>Hello, {{ name }}!</p> export class AppComponent { name = 'Angular'; } ๐Ÿงฐ Structural Directives Structural directives shape or change the structure of the DOM . They start with an asterisk * . 1. ๐Ÿงพ *ngIf – Conditional Rendering Renders the element only if the condition is true . <p *ngIf="isLoggedIn">Welcome back!</p> <p *ngIf="!isLoggedIn">Please log in.</p> isLoggedIn = true; You can also use else : <div *ngIf="items.length > 0; else noItems"> <p>Items available!</p> </div> <ng-template #noItems> <p>No items found.</p> </ng-templat...

Why Metadata is Important in Angular

๐Ÿงฉ What is a Component Decorator? The @Component decorator is a TypeScript decorator that tells Angular: "Hey, this class is a component and here’s some extra information about it." It's applied above the class definition and includes a metadata object . ๐Ÿ”ง Basic Syntax import { Component } from '@angular/core'; @Component({ selector: 'app-my-component', templateUrl: './my-component.component.html', styleUrls: ['./my-component.component.css'] }) export class MyComponent { // Component logic here } ๐Ÿ“ฆ Metadata Properties Breakdown Property Description selector The name used to include the component in HTML ( <app-my-component> ). template Inline HTML template. templateUrl External HTML file for the template. styles Inline styles for the component. styleUrls External CSS or SCSS files. providers List of services/providers available only to this ...

Creating an Angular Component

Creating components is a core concept in Angular because components are the building blocks of any Angular application. ๐Ÿ”น What is an Angular Component? A component in Angular controls a view (HTML template) and contains logic to support that view (written in a TypeScript class). It typically consists of: A .ts file (logic) A .html file (template) A .css or .scss file (styling) ๐Ÿ”ง How to Create a Component ✅ Using Angular CLI (recommended) ng generate component component-name # OR ng g c component-name For example: ng g c user-profile This creates a folder like this: src/app/user-profile/ ├── user-profile.component.ts ← component logic ├── user-profile.component.html ← template ├── user-profile.component.css ← styles ├── user-profile.component.spec.ts ← test file ๐Ÿงฑ Anatomy of a Component user-profile.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-user-profile', temp...