Advanced Web Designing — Study Notes

Unit 03 & 04

Angular fundamentals — lifecycle hooks, directives, data binding, pipes, forms, modules, services & DI, and routing — organized as exam-ready answers.

8 Questions 5 Marks Each Advanced Web Designing
01
5 Marks Question

Explain Angular Component Lifecycle Hooks

Angular Component Lifecycle Hooks are special methods provided by Angular that allow developers to perform actions at different stages of a component's life.

A component goes through different stages such as creation, change detection, and destruction. Lifecycle hooks allow us to execute code at these stages.

Important Lifecycle Hooks

01
ngOnInit()

ngOnInit() runs when the component is initialized or created. It is commonly used for loading data, initializing variables, and calling APIs.

Example
ngOnInit() {
  console.log("Component started");
}
02
ngOnChanges()

ngOnChanges() runs when a value received by the component changes. It is useful when a component receives data from another component and that data changes.

Example
ngOnChanges() {
  console.log("Value changed");
}
03
ngDoCheck()

ngDoCheck() is used when Angular performs change checking. It allows the developer to perform custom checking when changes need to be detected.

Example
ngDoCheck() {
  console.log("Checking changes");
}
04
ngOnDestroy()

ngOnDestroy() runs just before the component is removed or destroyed. It can be used to perform cleanup operations before the component is removed.

Example
ngOnDestroy() {
  console.log("Component removed");
}

Summary Table

Lifecycle HookWhen it runsMain Purpose
ngOnInit()When component is initializedLoad data, initialize variables, call API
ngOnChanges()When received value changesRespond to changed input data
ngDoCheck()During Angular change checkingPerform custom change checking
ngOnDestroy()Before component is removedCleanup before destruction
ConclusionAngular lifecycle hooks provide a way to execute specific code during important stages of a component's life. The important hooks covered here are ngOnInit(), ngOnChanges(), ngDoCheck(), and ngOnDestroy(), which handle initialization, changes, change checking, and destruction respectively.
02
5 Marks Question

Explain Angular Directives — *ngIf, *ngFor, *ngSwitch, ngClass

Directives are special instructions in Angular that are used to change the behavior, structure, or appearance of HTML elements dynamically. Angular directives can be broadly used to control how elements are displayed and how they behave.

01
*ngIf

*ngIf is a structural directive used to show or hide an HTML element based on a condition.

Example
<p *ngIf="isLoggedIn">
    Welcome User
</p>

If isLoggedIn is true, the paragraph is displayed; otherwise, it is not displayed.

02
*ngFor

*ngFor is a structural directive used to repeat an HTML element for each item in a collection.

Example
<ul>
    <li *ngFor="let student of students">
        {{ student }}
    </li>
</ul>

Here, the <li> element is repeated for every student in the students collection.

03
*ngSwitch

*ngSwitch is used when there are multiple possible choices. It works with *ngSwitchCase, which defines individual cases, and *ngSwitchDefault, which executes when no case matches.

Example
<div [ngSwitch]="day">

    <p *ngSwitchCase="'Monday'">Start of week</p>

    <p *ngSwitchCase="'Friday'">End of week</p>

    <p *ngSwitchDefault>Other day</p>

</div>

The appropriate content is displayed based on the value of day.

04
ngClass

ngClass is an attribute directive used to add or remove CSS classes dynamically based on a condition.

Example
<p [ngClass]="isSuccess ? 'success' : 'danger'">
    Result
</p>

If isSuccess is true, the success CSS class is applied; otherwise, the danger class is applied.

Summary

DirectiveTypePurpose
*ngIfStructuralShows or hides elements based on a condition
*ngForStructuralRepeats elements for each item in a collection
*ngSwitchStructuralSelects content from multiple choices
ngClassAttributeDynamically adds or removes CSS classes
ConclusionAngular directives make HTML dynamic and interactive. Structural directives such as *ngIf, *ngFor, and *ngSwitch control the structure of the page, while ngClass dynamically changes the styling of elements.
03
5 Marks Question

Explain Data Binding in Angular

Data Binding in Angular is a mechanism used to establish a connection between the component's TypeScript data and the HTML template. It allows data to be displayed in the UI and allows user actions to interact with component data.

Angular provides four main types of data binding.

01
Interpolation

Interpolation is used to display TypeScript data in the HTML template.

Syntax
{{ expression }}
Example
name = "Farhan";

<p>Student Name: {{ name }}</p>

The value of name is displayed in the HTML.

02
Property Binding

Property binding is used to set an HTML element's property using a TypeScript value.

Syntax
[property]="value"
Example
<button [disabled]="isDisabled">
    Submit
</button>

Here, the disabled property of the button is controlled by the isDisabled variable.

03
Event Binding

Event binding is used to handle user actions or events and call a method in the component.

Syntax
(event)="method()"
Example
<button (click)="showMessage()">
    Click Me
</button>

When the button is clicked, the showMessage() method is called. Common events include (click), (mouseenter), (mouseleave), (input), (change), and (submit).

04
Two-Way Data Binding

Two-way data binding allows data to flow in both directions between the component and the HTML template. It uses [(ngModel)].

Example
<input [(ngModel)]="name">

<p>Hello {{ name }}</p>

When the user changes the input, the name variable is updated, and changes to name are reflected back in the input.

Summary Table

TypeSyntaxPurpose
Interpolation{{ }}Displays component data
Property Binding[ ]Sets HTML properties
Event Binding( )Handles user events
Two-Way Binding[(ngModel)]Synchronizes data in both directions
ConclusionData binding is an important feature of Angular that connects the TypeScript component and HTML template. The four main types are Interpolation, Property Binding, Event Binding, and Two-Way Data Binding, which together make Angular applications dynamic and interactive.
04
5 Marks Question

Explain Angular Built-in Pipes

Pipes in Angular are used to change or transform data before displaying it in the HTML template. They are written using the pipe symbol |.

Syntax
{{ value | pipe }}

Angular provides several built-in pipes for common data transformations.

Common Built-in Pipes

Uppercase Pipe
Converts text into uppercase letters. {{ name | uppercase }} — Example: farhan → FARHAN
Lowercase Pipe
Converts text into lowercase letters. {{ "HELLO" | lowercase }} — Output: hello
Titlecase Pipe
Converts text into title case. {{ name | titlecase }}
Currency Pipe
Formats a number as a currency value. {{ price | currency }} — For Indian Rupees: {{ price | currency:'INR' }}
Date Pipe
Formats a date according to the specified format. {{ today | date:'dd/MM/yyyy' }}
Percent Pipe
Formats a number as a percentage. {{ result | percent }}
Slice Pipe
Displays a portion of a string or collection. {{ name | slice:0:3 }} — displays characters from index 0 up to index 3.

Summary Table

PipePurposeExample
uppercaseConverts text to uppercase{{ name | uppercase }}
lowercaseConverts text to lowercase{{ name | lowercase }}
titlecaseConverts text to title case{{ name | titlecase }}
currencyFormats currency{{ price | currency:'INR' }}
dateFormats dates{{ today | date:'dd/MM/yyyy' }}
percentFormats percentage{{ result | percent }}
sliceExtracts a portion of data{{ name | slice:0:3 }}

Custom Pipe

Angular also allows developers to create custom pipes. A custom pipe can be generated using:

ng generate pipe greeting

or

ng g pipe greeting
ConclusionAngular built-in pipes make it easy to transform and format data directly in HTML templates. Common pipes include uppercase, lowercase, titlecase, currency, date, percent, and slice.
05
5 Marks Question

Explain Forms and Form Validation in Angular

Forms in Angular are used to collect user input and process data submitted by the user. Angular provides two main approaches for creating forms: Template-driven forms and Reactive forms.

Form validation is used to ensure that the data entered by the user satisfies required conditions such as required, email, minlength, and pattern.

01
Template-Driven Forms

In template-driven forms, most of the form is controlled from the HTML template. It is simpler and suitable for basic forms. It uses ngForm and ngModel.

Example
<form #studentForm="ngForm"
      (ngSubmit)="submitForm(studentForm)">

    <label>Name:</label>
    <input type="text" name="studentName" ngModel>

    <button type="submit">Submit</button>
</form>
TypeScript
submitForm(studentForm: any) {
    console.log(studentForm.value);
}

Here, #studentForm creates a template reference, ngForm tells Angular to treat the form as an Angular form, ngModel binds the input to the form, and ngSubmit handles form submission.

02
Reactive Forms

In reactive forms, the form structure and controls are mainly created and managed in the TypeScript file. It uses FormGroup and FormControl.

Example
<form [formGroup]="studentForm"
      (ngSubmit)="submitForm()">

    <input formControlName="studentName">
    <input formControlName="email">

    <button type="submit">Submit</button>
</form>
TypeScript
studentForm = new FormGroup({
    studentName: new FormControl(''),
    email: new FormControl('')
});

submitForm() {
    console.log(this.studentForm.value);
}

Reactive forms are more structured and are suitable for complex forms.

Form Validation

Form validation checks whether the data entered by the user is valid according to specified rules. These validations can be used to prevent invalid or incomplete data from being submitted.

required
Field must contain a value.
email
Checks for a valid email format.
minlength
Specifies the minimum length.
pattern
Checks whether the input matches a specified pattern.

Template-Driven vs Reactive Forms

FeatureTemplate-DrivenReactive
Main controlHTML templateTypeScript
Commonly usesngModelFormControl, FormGroup
ComplexitySimpleMore structured
CodeLess codeMore code
Suitable forSimple formsComplex forms
ConclusionAngular provides Template-driven and Reactive forms for collecting and managing user input. Template-driven forms are simpler and mainly controlled through HTML, while Reactive forms provide a more structured approach through TypeScript. Form validation ensures that entered data satisfies rules such as required, email, minlength, and pattern.
06
5 Marks Question

Explain Modules in Angular with Example

Modules in Angular are used to group related components, services, and other application features together. They help organize an Angular application into manageable parts.

Angular applications can have a root module (AppModule) and additional feature modules for specific parts of the application.

Types of Modules

Root Module
The main module of an Angular application, commonly called AppModule. It acts as the starting point of the application.
Feature Modules
Used to group components and functionality related to a particular feature — for example, a student management application could have a Student Module, Course Module, and Admin Module. This makes the application easier to organize and maintain.

Example

A simple module can be defined using @NgModule:

import { NgModule } from '@angular/core';

@NgModule({
  declarations: [],
  imports: [],
  providers: [],
  bootstrap: []
})
export class AppModule {
}

Here, @NgModule defines the Angular module and its configuration.

Simple Structure

Angular Application
       |
    AppModule
       |
   ┌───┴────┐
   |        |
Student   Course
Module    Module
   |        |
Components Components

Thus, modules provide a way to organize related functionality into separate sections of an Angular application.

ConclusionAngular modules help organize an application by grouping related components, services, and features. The application has a root AppModule, while feature modules can be created for specific functionality, making large applications easier to structure and manage.
07
5 Marks Question

Explain Services and Dependency Injection in Angular

01
Angular Service

An Angular Service is a class used to store reusable data and functionality that can be shared by different components. Services help avoid repeating the same code in multiple components.

A service can be created using the Angular CLI:

ng generate service student

or:

ng g service student
Example of a Service
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class StudentService {

  getStudent() {
    return "Farhan";
  }
}

Here, StudentService contains the reusable getStudent() method. The providedIn: 'root' configuration makes the service available throughout the application.

02
Dependency Injection (DI)

Dependency Injection is a mechanism in Angular through which Angular provides a required service to a component instead of the component creating the service itself. This makes components easier to manage and allows them to use reusable services.

Example
import { StudentService } from './student.service';

constructor(private studentService: StudentService) {
}

Here, StudentService is injected into the component through the constructor. Angular provides the required service automatically.

Working

The basic working can be represented as:

Component
    |
    | requests service
    ↓
Dependency Injection
    |
    | provides
    ↓
StudentService
    |
    ↓
Reusable Data / Functionality

Advantages

Code reusability
Common functionality can be placed in one service.
Better organization
Business or reusable functionality is separated from components.
Easy sharing
Multiple components can use the same service.
Simpler components
Components do not need to create services themselves.
ConclusionServices provide reusable data and functionality in Angular, while Dependency Injection allows Angular to provide those services to components when required. Together, they promote code reusability, organization, and easier application development.
08
5 Marks Question

Explain Routing and Navigation in Angular

Routing in Angular is used to navigate between different views or components of an application. It allows users to move from one page/component to another without reloading the entire browser page. Angular routing is especially useful for building Single Page Applications (SPAs).

Working of Routing

Angular routing connects a URL path with a particular component. For example:

URL                    Component
------------------------------------------------
/home       →          HomeComponent
/student    →          StudentComponent
/about      →          AboutComponent

When the user navigates to a particular URL, Angular displays the corresponding component without refreshing the complete webpage.

Example

A simple routing configuration can be represented as:

const routes = [
  { path: 'home', component: HomeComponent },
  { path: 'student', component: StudentComponent },
  { path: 'about', component: AboutComponent }
];

Here, home displays HomeComponent, student displays StudentComponent, and about displays AboutComponent.

Navigation can then be provided through links such as:

<a routerLink="/home">Home</a>
<a routerLink="/student">Student</a>
<a routerLink="/about">About</a>

Advantages of Routing

Component navigation
Allows navigation between different components.
No full reloads
Avoids complete browser-page reloads.
SPA support
Supports Single Page Applications.
Structured views
Provides a structured way to manage different views of an application.
ConclusionAngular Routing and Navigation provide a mechanism for moving between different components or views using URLs. It enables smooth navigation without reloading the entire browser page and is an important feature for developing Single Page Applications (SPAs).