Skip to main content

Posts

Showing posts with the label Angular

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

Employee Management System with Angular

Introduction In this tutorial, we will build an Employee Management System using Angular. This exercise demonstrates essential Angular concepts, including Angular Components, Data Binding, Interpolation, Property Binding, Event Binding, Two-way Data Binding, and Child/Nested Components. Objective Create an Employee Management System that allows you to manage a list of employees, demonstrating key Angular concepts. Requirements 1. Main Application Component Set up a new Angular project. Create the main application component. 2. Employee List Component Create `EmployeeListComponent` to display a list of employees. Use interpolation to display employee names and other details. Use property binding to dynamically set CSS classes based on employee properties (e.g., highlight employees with more than 5 years of experience). 3. Employee Detail Component Create a nested component called `EmployeeDetailComponent` to show detailed information about a selected employee. Use `@Input` to pass th...

Angular : simple contact list

Introduction In this blog post, I will demonstrate how to create a simple contact list application using Angular. This application allows users to add, view, and delete contacts. It is a great project for those looking to get started with Angular and understand the basics of data binding, event handling, and component interaction. Features Add new contacts View the list of contacts Delete contacts Getting Started To get started, ensure you have Angular CLI installed. You can create a new Angular project using the following command: ng new contact-list-app Navigate to your project directory cd contact-list-app Code Snippet Below is a snippet of the main component code for the contact list application. This includes the component decorator and the logic for managing the contacts. import { Component } from '@angular/core'; import {FormsModule} from "@angular/forms"; import {NgForOf} from "@angular/common"; in...

Angular: building basic calculator

Introduction In this tutorial, we will walk through the steps to create a simple calculator application using Angular. This exercise is designed to help you practice your Angular skills and understand the basics of building a user interface and handling events. Prerequisites Before you begin, ensure you have the following: Basic understanding of Angular Angular CLI installed Node.js and npm installed Step 1: Setting Up the Project First, let's create a new Angular project. Open your terminal and run: ng new BasicCalculator  cd BasicCalculator  ng serve This will set up a new Angular project and start the development server. You can view the default application by navigating to http://localhost:4200 in your browser. Step 2: Designing the Calculator UI In app.component.html, design the UI of the calculator. Here's a simple structure to get you started: <div class="container"> <div class="calculator"> <div><input class=...

Building an Angular App: To-Do list

Introduction In this post, I'll share my experience building a small Angular application called "To-Do List". This is a practice project to delve deeper into Angular concepts. Application Overview Simple angular application Basic Angular concepts No API calls Pure front-end implementation Code Snippet app.component.html <div class="container-fluid"> <div class="container"> <div class="row align-items-center"> <div class="col-4"> <div class="card"> <div class="card-header"> <label for="exampleFormControlInput1" class="form-label">Add to-do</label> </div> <div class="card-body"> <h5 class="card-title">New Do It</h5> <input type="text" class="form-control" [(ngModel)]="toDoValue" i...

Angular : Setup

Download Node.js Download Node.js NVM (Node Version Manager) Download and install NVM: GitHub - coreybutler/nvm-windows Command: Install a version of Node: nvm install 14.15.1 Use a version installed: nvm use 14.15.1 List all installed Node versions: nvm list Install Angular CLI npm -g @angular/cli Create Project Create a new Angular project: ng new [AppName] Or with a specified prefix: ng new [AppName] --prefix [PrefixName] All generated components will have the prefix in the selector o...

Angular : introduction

Features of Angular Two-Way Data Binding Data binding is automatic and fast. Changes made in the View are automatically updated in the component class and vice versa. Powerful Routing Support The Angular Powerful routing engine loads the page asynchronously on the same page, enabling us to create Single Page Applications. Expressive HTML Angular enables us to use programming constructs like if conditions, for loops, etc., to render and control HTML pages. Modular by Design Angular follows the modular design. You can create Angular modules to better organize and manage our codebase. Built-in Back End Support Angular has built-in support to communicate with the back-end servers and execute any business logic or retrieve data...

Angular: Architecture overview and concepts

The first big change in Angular over AngularJs is Components. Components replace the Controllers of AngularJs. But that is where the similarity ends. Angular Components do not look like Controllers. The Components are actually similar to the directives of AngularJs. Angular Architecture The architecture of an Angular Application is based on the idea of Components. An Angular application starts with a Top-level component called Root Component. We then add child components forming a tree of loosely coupled components. Angular Modules The Angular provides a nice way to organize Components, Services, Directives by using the concept called Angular Modules. Special directives are used to create the Modules. The Angular Module is also called ngModule. Use Angular Module (or ngModule) to organize all the Angular code within a bigger Angular Application. The Application is made up of several Angular Modules acting toge...

Angular: Creating new project

What is Angular CLI The Angular CLI helps us to quickly create an Angular application with all the configuration files and packages in one single command. It also helps us to add features (components, directives, services, etc) to existing Angular applications. The Angular CLI creates the Angular Application and uses: Typescript, Webpack ( for Module bundling), Karma ( for unit testing), Protractor ( for an end-to-end testing). How to Create a new Angular project Before starting with Angular, you need to set up your developer environment and install the required tools. Before going further install the following: Visual Studio Code (or any other editor of your choice) NPM Package Manager Installing Angular CLI The first step is to install the Angular CLI. We use the npm install command. npm install -g @angular/cli@latest The above command installs the latest version...

Angular: Bootstrapping in angular

What is Bootstrapping? Bootstrapping is a technique of initializing or loading our Angular application. Let’s walk through the code created in "Create your First new Angular project" and see what happens at each stage and how our AppComponent gets loaded and displays “app works!”. Angular takes the following steps to load our first view: Index.html loads: The initial HTML file is loaded into the browser. Angular, Third-party libraries & Application loads: Angular framework and any third-party libraries are loaded. Main.ts - the application entry point: The main.ts file is executed, which bootstraps the Angular application. Root Module: The root module ( AppModule ) is loaded. This module organizes the application code and defines the components, services, and other features used in the application. Root Component: The root component ( AppComponent ) is loaded. This component serves as the starting point of the application and is defin...