Skip to main content

Posts

Showing posts with the label Angular Roadmap

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...

Modules and Namespaces in TypeScript

Modules and Namespaces in TypeScript Modules and Namespaces in TypeScript Let’s break down Modules and Namespaces in TypeScript — both are mechanisms for organizing and reusing code, but they serve slightly different purposes and are used differently. ๐Ÿ”น Modules in TypeScript ✅ What is a Module? A module is a file that contains code (classes, interfaces, functions, variables, etc.) and exports them so they can be reused in other files by importing . ๐Ÿ”ง How to Create and Use a Module math.ts (a module) export function add(a: number, b: number): number { return a + b; } export const PI = 3.14; main.ts (importing the module) import { add, PI } from './math'; console.log(add(5, 10)); // 15 console.log(PI); // 3.14 Modules follow ES6 module syntax and are commonly used in Angular and modern TypeScript projects. ๐Ÿ”น Namespaces in TypeScript ✅ What is a Namespace? ...

Classes and Objects in TypeScript

Classes and Objects in TypeScript Classes and Objects in TypeScript Awesome! Let's now cover Classes and Objects in TypeScript, which are at the core of building services, components, and models in Angular. ๐Ÿ”น 1. What is a Class? A class is a blueprint for creating objects. It encapsulates data (properties) and behavior (methods). ✅ Basic Syntax class Person { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } greet(): void { console.log(`Hello, my name is ${this.name}`); } } ๐Ÿ”น 2. Creating an Object You can create objects (instances) from a class using the new keyword. const person1 = new Person("Alice", 30); person1.greet(); // Output: Hello, my name is Alice ๐Ÿ”น 3. Access Modifiers Modifier Description ...

Variables, Data Types, and Interfaces in Angular (TypeScript)

Variables, Data Types, and Interfaces in Angular (TypeScript) Variables, Data Types, and Interfaces in Angular (TypeScript) These are foundational concepts that make your Angular app type-safe, scalable, and easier to maintain. ๐Ÿ”น 1. Variables in TypeScript TypeScript is strongly typed, so you can (and should) define the type of your variables. ✅ Syntax: let name: string = "Angular"; const version: number = 17; var isAwesome: boolean = true; ๐Ÿ”„ `let` vs `const` vs `var`: Keyword Scope Reassignable Hoisted `let` Block ✅ Yes ❌ No `const` Block ❌ No ❌ No `var` Function ✅ Yes ✅ Yes ๐Ÿ”น 2. Data Types in TypeScript ...

Angular Project Structure

Angular Project Structure ๐Ÿ“ Angular Project Structure Overview ๐Ÿ”น `e2e/` End-to-End Testing folder using Protractor or Cypress. Contains tests that simulate real user interactions. ๐Ÿ”น `node_modules/` Contains all installed npm packages. Automatically generated—no need to modify this manually. ๐Ÿ”น `src/` (This is where the real magic happens) ๐Ÿ”ธ `app/` Your main application logic lives here. Contains components, services, modules, etc. File Description app.module.ts Root module that bootstraps your app. app.component.ts Logic/controller of the root component. ...

Creating Your First Angular App

Creating Your First Angular App ✅ Prerequisites Make sure you have: Node.js installed ( node -v ) Angular CLI installed ( ng version ) If not, install with: npm install -g @angular/cli ๐Ÿš€ Step-by-Step: Create Your Angular App ๐Ÿ”ง Step 1: Create the App Run this command in your terminal: ng new my-first-app You’ll be prompted with: Would you like to add Angular routing? → Type Yes or No Which stylesheet format would you like to use? → Choose CSS (or SCSS, etc.) This will generate a new folder my-first-app with the full Angular project structure. ๐Ÿ“‚ Step 2: Navigate to the Project cd my-first-app ๐Ÿงช Step 3: Serve the Application ng serve By default, the app runs on http://localhost:4200 . Open your bro...

Angular Setup Guide

Angular Setup Guide ๐Ÿ› ️ 1. Install Node.js & npm Angular requires Node.js (includes npm - Node Package Manager). ✅ Download & Install: Go to https://nodejs.org Download the LTS version (recommended for most users). Follow the installer instructions for your OS (Windows, macOS, Linux). ๐Ÿ” Verify Installation: node -v npm -v ๐ŸŸข 2. Install Angular CLI (Command Line Interface) The Angular CLI is a powerful tool to scaffold, build, serve, and manage Angular projects. ๐Ÿ“ฅ Install Globally: npm install -g @angular/cli ๐Ÿ” Verify Installation: ng version ๐Ÿงช 3. Create Your First Angular App ng new my-angular-app You’ll be prompted to: Choose if you want to add Angular routing → (Yes/No) Choose a stylesheet format (CSS, SC...

What is Angular?

Angular Notes ๐ŸŸ  What is Angular? Angular is a TypeScript-based open-source web application framework developed and maintained by Google . It is a complete platform for building dynamic, single-page client applications (SPAs) in HTML and TypeScript. Angular provides a structured and scalable approach to building modern web applications using features like: Component-based architecture Two-way data binding Dependency injection Routing Reactive programming Built-in form handling and validation CLI for scaffolding and automation Angular is the successor to AngularJS (the original version), but it’s a complete rewrite and far more modern. ✅ Why Use Angular? Here are some key reasons developers and teams choose Angular: 1. Component-Based Architecture Breaks ...