Advanced Web Designing — External Study Notes

Unit 03 & 04

Angular exam-ready Q&A — modules, services, routing, lifecycle hooks, directives, data binding, pipes, forms & HttpClient — renumbered and grouped by mark weightage.

22 Questions 5 × 2 Marks + 17 × 5 Marks Angular · External
Part A

2 Marks Questions

Short, precise answers — one clear definition and example per question.

01
2 Marks Question

Explain AngularJS $routeProvider Service with an Example

The AngularJS $routeProvider service is used to configure different routes (URLs) and associate each route with a particular view and controller. It allows a single-page application to change views without loading a completely new page.

Example
$routeProvider.when('/home', {
    templateUrl: 'home.html',
    controller: 'HomeController'
});

Here, /home displays home.html and uses HomeController.

$routeProvider is AngularJS terminology and is not explicitly covered in the provided Unit 3 & 4 notes; it is included here as supplementary material.
02
2 Marks Question

Explain ngStyle Directive

ngStyle is an Angular attribute directive used to change CSS styles dynamically according to component data.

Example
colorValue = "blue";

<p [ngStyle]="{'color': colorValue}">
    Hello Students
</p>

Here, the text color is changed dynamically using the value of colorValue.

03
2 Marks Question

Explain Custom Directives

A custom directive is a directive created by the developer to add custom behavior or styling to an HTML element. It can be generated using the Angular CLI.

Command
ng generate directive highlight

or

ng g directive highlight

Angular creates a directive file such as highlight.directive.ts.

04
2 Marks Question

Explain Custom Pipes

A custom pipe is a user-defined Angular pipe created to perform a custom transformation or formatting of data before displaying it in HTML. It can be created using:

ng generate pipe greeting

or

ng g pipe greeting
05
2 Marks Question

Explain Observables with RxJS

An Observable is used in Angular to handle asynchronous data and data that arrives over time. Angular uses RxJS (Reactive Extensions for JavaScript) to work with Observables. A component subscribes to an Observable to receive its values.

Example
data.subscribe(value => {
    console.log(value);
});

Here, subscribe() means that the component wants to receive the data emitted by the Observable.

Part B

5 Marks Questions

Detailed, structured answers with examples, diagrams and comparison tables.

01
5 Marks Question

Explain Modules in Angular with an Example

An Angular module is a container that groups related components, services and other code together. Modules help organize a large Angular application into manageable and reusable parts. Every Angular application has at least one main/root module called AppModule. In a large application, separate feature modules can be created for different areas of the system — for example, a hospital management system may have PatientModule, AppointmentModule and BillingModule.

Main Features of Angular Modules

Organization
Modules keep related functionality together instead of putting everything into one large application structure.
Reusability
Related code can be grouped and reused within the application.
Separation of Features
Large applications can be divided into feature modules according to their functions.
Maintainability
A modular application is easier to understand, modify and maintain.
Root Module
Every Angular application has a root module such as AppModule.

Example

Suppose a college application contains student, course and fee features:

College Application
       |
       +-- StudentModule
       +-- CourseModule
       +-- FeeModule

StudentModule can contain components and services related to student information, CourseModule can contain course-related functionality, and FeeModule can contain fee-related functionality.

ConclusionModules provide a structured way to organize Angular applications and make large applications easier to develop, understand and maintain.
02
5 Marks Question

Explain Services and Dependency Injection with an Example

01
Angular Service

An Angular Service is a class used to store reusable data and functionality that can be shared by different components. Instead of writing the same functionality in multiple components, a service can provide it from one common place.

Generate via CLI
ng generate service student

or

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

@Injectable({
  providedIn: 'root'
})
export class StudentService {
  getStudent() {
    return "Farhan";
  }
}

Here, @Injectable tells Angular that the class can be used as a service, and providedIn: 'root' makes it available to the application.

02
Dependency Injection (DI)

Dependency Injection (DI) is a mechanism in Angular where Angular provides a required service to a component instead of the component creating the service itself. This keeps code clean, reusable and easier to manage.

Example
constructor(private studentService: StudentService) {
}

showStudent() {
  console.log(this.studentService.getStudent());
}

Working

Component
    |
    | requests StudentService
    v
Angular DI
    |
    v
StudentService
    |
    v
getStudent()
ConclusionServices contain reusable functionality, while Dependency Injection provides those services to components automatically. Together they reduce code duplication and improve the organization and reusability of an Angular application.
03
5 Marks Question

Explain Routing and Navigation in Angular

Routing in Angular is the built-in mechanism used to navigate between different pages or views of an application. Angular routing allows navigation without the browser actually reloading the complete page, giving Angular applications the smooth, app-like behavior expected from a Single Page Application (SPA).

Purpose of Routing

Navigate between views
Allows users to move between different views/pages.
SPA support
Supports Single Page Applications.
No full reloads
Avoids complete browser-page reloads during navigation.
Organized views
Makes large applications easier to organize into different views.

Example

Suppose an application has three views:

/home      -> Home page
/students  -> Student page
/about     -> About page

The user can move from Home to Students or About while Angular changes the displayed view without reloading the whole application. A simple conceptual route configuration is:

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

Navigation then selects the required route and Angular displays the corresponding component.

ConclusionAngular Routing provides smooth navigation between application views and is an important part of building Single Page Applications.
04
5 Marks Question

Explain Modules and Controllers with an Example

The phrase "Modules and Controllers" uses AngularJS terminology. The provided Unit 3 & 4 notes discuss Angular Modules and MVC architecture, but do not explicitly teach AngularJS controller syntax — the answer below uses the standard AngularJS interpretation.

AngularJS Module

A module is a container that groups related controllers, services, directives and other application components. It acts as the starting structure of an AngularJS application.

var app = angular.module('studentApp', []);

Here, studentApp is the AngularJS module name and [] represents its dependencies.

Controller

A controller is a JavaScript function/object that contains the data and behavior used by a particular view. It acts as a bridge between the application's data and the HTML view.

app.controller('StudentController', function($scope) {
  $scope.name = "Farhan";
  $scope.course = "BCA";
});
<div ng-app="studentApp" ng-controller="StudentController">
    <h2>{{name}}</h2>
    <p>{{course}}</p>
</div>

Working

Module
  |
  +-- Controller
          |
          +-- Data / Logic
                  |
                  v
                View
ConclusionAn AngularJS module organizes the application, while a controller manages the data and logic used by a view.
05
5 Marks Question

Explain Angular Components and How to Create a Component using @Component

A component is a small, independent and reusable block of the Angular user interface. Angular follows a component-based architecture in which the complete UI is divided into multiple components. Each component has three main parts:

HTML file
Defines what the component displays.
TypeScript file
Contains the component's logic and data.
CSS file
Controls the component's styling.

Creating a Component

Angular provides the @Component decorator to create or define a component. A component can be generated using the Angular CLI:

ng generate component student

or

ng g c student
TypeScript Example
import { Component } from '@angular/core';

@Component({
  selector: 'app-student',
  imports: [],
  templateUrl: './student.html',
  styleUrl: './student.css'
})
export class StudentComponent {
  name = "Farhan";
  course = "BCA";
}

Here, @Component marks the class as an Angular component, selector defines the HTML tag used to display the component, templateUrl specifies the HTML template, styleUrl specifies the CSS file, and StudentComponent is the TypeScript class containing the component's logic.

HTML Template
<h1>Student Details</h1>
<p>Student Name: {{ name }}</p>
<p>Course: {{ course }}</p>

The component can then be used in the application template as:

<app-student></app-student>
ConclusionComponents are the basic building blocks of an Angular UI. The @Component decorator connects the component class with its selector, template and styling.
06
5 Marks Question

Explain Angular Component Lifecycle Hooks

Angular component lifecycle hooks are special methods that run at important stages in the life of an Angular component. They allow the developer to perform actions when a component is created, checked, changed or destroyed.

Important Lifecycle Hooks

01
ngOnInit()

Runs when the component is initialized/created. Common uses include loading data, initializing variables, and calling an API.

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

Runs when a value received by the component changes.

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

Used when Angular performs change checking.

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

Runs just before the component is removed or destroyed.

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

Lifecycle Flow

Component Created
      |
      v
  ngOnInit()
      |
      v
Change Checking
      |
      v
  ngDoCheck()
      |
      v
Component Destroyed
      |
      v
  ngOnDestroy()

ngOnChanges() can run when an input value received by the component changes.

ConclusionLifecycle hooks provide controlled points where developers can initialize data, react to changes and perform cleanup when an Angular component is destroyed.
07
5 Marks Question

Explain Component Communication using Input, Output and EventEmitter

Component communication means sending data or events between two or more Angular components. The main mechanisms are @Input() for parent-to-child communication and @Output() with EventEmitter for child-to-parent communication.

01
@Input() — Parent to Child

@Input() is used when the parent component sends data to the child component.

Parent TypeScript
export class AppComponent {
  studentName = "Rahul";
}
Parent HTML
<app-student [name]="studentName"></app-student>
Child TypeScript
import { Component, Input } from '@angular/core';

export class StudentComponent {
  @Input() name = "";
}

Here, [name]="studentName" sends the parent's studentName value to the child's name property.

02
@Output() and EventEmitter — Child to Parent

@Output() is used when the child needs to send an event/data back to the parent. EventEmitter is used to create and emit the event.

Child Component
@Output() studentEvent = new EventEmitter<string>();

sendMessage() {
  this.studentEvent.emit("Hello from Student");
}
Parent Template
<app-student
    (studentEvent)="receiveMessage($event)">
</app-student>

Data Flow

Parent
  |
  | @Input()
  v
Child
  |
  | @Output() + EventEmitter
  v
Parent
Conclusion@Input() is used for parent-to-child data transfer, while @Output() and EventEmitter are used for child-to-parent communication.
08
5 Marks Question

Explain *ngIf, *ngFor, *ngSwitch and ngClass Directives

A directive is an instruction given to Angular that tells Angular how to change or control HTML elements. Directives can show/hide elements, repeat elements, select among multiple choices, or change CSS classes.

01
*ngIf

Structural directive used to show or hide an element based on a condition.

isStudent = true;

<h2 *ngIf="isStudent">
    Welcome Student
</h2>

The heading is displayed only when isStudent is true.

02
*ngFor

Used to repeat an HTML element for each item in a collection.

students = ['Rahul', 'Amit', 'Neha'];

<p *ngFor="let student of students">
    {{ student }}
</p>

Angular creates one <p> element for each student.

03
*ngSwitch

Used when there are multiple possible choices — works similarly to a normal JavaScript switch statement.

day = 'Monday';

<div [ngSwitch]="day">
    <p *ngSwitchCase="'Monday'">Today is Monday</p>
    <p *ngSwitchCase="'Tuesday'">Today is Tuesday</p>
    <p *ngSwitchDefault>Other Day</p>
</div>

Angular displays the case that matches the value of day.

04
ngClass

An attribute directive used to add or remove CSS classes dynamically.

.success { color: green; }
.danger  { color: red; }

isSuccess = true;

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

The class changes according to the value of isSuccess.

Summary

*ngIf     -> Show/hide based on condition
*ngFor    -> Repeat elements
*ngSwitch -> Select among multiple choices
ngClass   -> Add/remove CSS classes dynamically
ConclusionThese directives make Angular templates dynamic and allow the interface to respond to conditions, collections, choices and application data.
09
5 Marks Question

Explain Data Binding in Angular

Data binding means connecting data in the TypeScript component with the HTML page. It allows information to move between the component and the user interface. Angular provides four main types of data binding.

01
Interpolation {{ }}

Displays TypeScript data in HTML.

studentName = "Rahul";
age = 20;

<h2>{{ studentName }}</h2>
<p>Age: {{ age }}</p>
02
Property Binding [ ]

Sets an HTML property using a TypeScript value.

isDisabled = true;

<button [disabled]="isDisabled">
    Submit
</button>

The button's disabled property is controlled by the TypeScript variable.

03
Event Binding ( )

Performs an action when the user performs an event such as clicking, typing, moving the mouse or submitting a form.

showMessage() {
  alert("Hello Students");
}

<button (click)="showMessage()">
    Click Me
</button>

Common events include click, mouseenter, mouseleave, input, change and submit.

04
Two-Way Data Binding [(ngModel)]

Allows data to move both from TypeScript to HTML and from HTML to TypeScript.

studentName = "";

<input [(ngModel)]="studentName">
<p>{{ studentName }}</p>

When the user types in the input field, studentName is updated and the paragraph automatically displays the new value.

Summary

Interpolation     -> Display data
Property Binding  -> Set element properties
Event Binding     -> Respond to user events
Two-Way Binding   -> Synchronize data in both directions
ConclusionData binding connects Angular component data with the HTML template and makes Angular applications dynamic and interactive.
10
5 Marks Question

Explain Interpolation, Property Binding, Event Binding and Two-way Binding

Angular provides four major forms of data binding. Each type defines how information moves between the component's TypeScript code and the HTML template.

01
Interpolation — {{ }}

Used to display TypeScript data inside HTML.

studentName = "Rahul";
age = 20;

<h2>{{ studentName }}</h2>
<p>Age: {{ age }}</p>

Output displays Rahul and 20 in the page.

02
Property Binding — [ ]

Sets an HTML property using a TypeScript value.

isDisabled = true;

<button [disabled]="isDisabled">
    Submit
</button>

The button is disabled when isDisabled is true.

03
Event Binding — ( )

Performs an action when the user performs an event.

showMessage() {
  alert("Hello Students");
}

<button (click)="showMessage()">Click Me</button>

Common events include (click), (mouseenter), (mouseleave), (input), (change), (submit).

04
Two-Way Data Binding — [(ngModel)]

Allows data to move from TypeScript to HTML and from HTML back to TypeScript.

studentName = "";

<input [(ngModel)]="studentName">
<p>{{ studentName }}</p>

When the user changes the input, studentName changes automatically; when the variable changes, the displayed value also updates.

ConclusionThe four binding types are different ways to connect component data and the HTML interface, making the application dynamic and interactive.
11
5 Marks Question

Explain Angular Built-in Pipes with Suitable Examples

A pipe is used to change the way data is displayed in HTML without changing the original data stored in the component. Angular provides several built-in pipes for common formatting operations.

01
uppercase

Converts text to capital letters.

name = "farhan kalkal";

<p>{{ name | uppercase }}</p>
02
lowercase

Converts text to small letters.

<p>{{ "HELLO" | lowercase }}</p>
03
titlecase

Makes the first letter of each word capital.

<p>{{ name | titlecase }}</p>
04
currency

Displays a number as money/currency.

<p>{{ price | currency }}</p>
<p>{{ price | currency:'INR' }}</p>

The second example displays the value using the Indian Rupee format.

05
date

Formats a date for display.

today = new Date();

<p>{{ today | date }}</p>
<p>{{ today | date:'dd/MM/yyyy' }}</p>

The second example formats the date in day/month/year form.

06
percent

Displays a decimal fraction as a percentage.

result = 0.75;

<p>{{ result | percent }}</p>

The percent pipe assumes that the value is a decimal fraction between 0 and 1.

07
slice

Takes only a part of a string or array.

name = "farhan";

<p>{{ name | slice:0:3 }}</p>

Summary

uppercase  -> Capital letters
lowercase  -> Small letters
titlecase  -> Capitalized words
currency   -> Currency formatting
date       -> Date formatting
percent    -> Percentage formatting
slice      -> Part of a string/array
ConclusionBuilt-in pipes make Angular templates easier to read by providing convenient data formatting directly in HTML.
12
5 Marks Question

Explain Angular Forms and Form Validation with an Example

Angular provides forms to collect and process user input. There are two main approaches: Template-driven Forms and Reactive Forms. Angular also supports validation to ensure that user-entered data satisfies required rules.

Common Validation Rules

required
Ensures that a field cannot be empty.
email
Checks for an email address format.
minlength
Ensures a minimum number of characters.
pattern
Checks whether the value matches a specified pattern.

Validation in a Template-driven Form

<form #myForm="ngForm">
    <label>Name:</label>
    <input type="text"
           name="studentName"
           ngModel
           required
           #studentName="ngModel">

    <p *ngIf="studentName.invalid && studentName.touched">
        Name is required.
    </p>

    <button type="submit" [disabled]="myForm.invalid">
        Submit
    </button>
</form>
Additional Validation Examples
<input type="email" name="email" ngModel required email>

<input type="password" name="password" ngModel minlength="6">

<input type="text" name="mobile" ngModel required
       pattern="[0-9]{10}" #mobile="ngModel">
Form TypeControlSuitable For
Template-drivenMainly controlled from HTML, uses ngModelSimple forms, beginners
ReactiveMainly controlled from TypeScript, uses FormControl/FormGroupComplex forms, stronger structure
ConclusionAngular forms provide a structured way to collect user data, while validation prevents incorrect or incomplete information from being accepted.
13
5 Marks Question

Explain Template-driven Forms

Template-driven forms are Angular forms in which most of the form logic is written and controlled in the HTML template. They are easier for beginners and are suitable for simple forms, using directives such as ngForm and ngModel.

Important Parts

FormsModule
Should be imported for template-driven forms.
#studentForm="ngForm"
Creates a template reference variable for the form.
ngModel
Connects form controls with Angular form handling.
ngSubmit
Used when the form is submitted.

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);
}

#studentForm="ngForm" tells Angular to treat the HTML form as an Angular form and creates a template reference variable. ngModel registers the input with the Angular form. (ngSubmit)="submitForm(studentForm)" calls submitForm() when the form is submitted, and studentForm.value contains the entered form data.

Validation Example

<input type="text"
       name="studentName"
       ngModel
       required
       #studentName="ngModel">

<p *ngIf="studentName.invalid && studentName.touched">
    Name is required.
</p>

<button type="submit" [disabled]="myForm.invalid">
    Submit
</button>

Advantages

Simple and beginner-friendly.
Requires less code for simple forms.
Logic is mainly handled in the HTML template.
ConclusionTemplate-driven forms are best suited for simple Angular forms where the form structure and validation can conveniently be expressed in the HTML template.
14
5 Marks Question

Explain Reactive Forms

Reactive Forms are Angular forms in which the form structure and logic are mainly controlled from TypeScript. They are more powerful and structured than template-driven forms and are suitable for complex forms. Reactive Forms commonly use FormGroup and FormControl.

HTML
<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);
}

Explanation

FormGroup
Represents the complete form as a group of controls.
FormControl
Represents an individual input/control.
formControlName
Connects an HTML input to a particular FormControl.
[formGroup]
Connects the HTML form to the FormGroup in TypeScript.
submitForm()
Can access the complete form value through this.studentForm.value.

Reactive forms are suitable for applying structured validation to complex forms — for example, rules can be created for required fields, email format, minimum length, and patterns.

Comparison with Template-driven Forms

BasisTemplate-drivenReactive
ControlMainly controlled from HTMLMainly controlled from TypeScript
LearningEasier for beginnersMore powerful and structured
CodeLess code for simple formsMore code
Directive/APIUses ngModelUses FormControl and FormGroup
Best forSimple formsComplex forms
ConclusionReactive Forms provide a structured and programmatic approach to form handling and are especially useful when the form is complex and requires stronger control over its state and validation.
15
5 Marks Question

Explain Services and Dependency Injection (Detailed)

01
Angular Service

An Angular Service is a class used to store reusable data and functionality that can be used by different components. A service avoids repeating the same functionality inside multiple components.

ng generate service student

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

@Injectable({
  providedIn: 'root'
})
export class StudentService {
  getStudent() {
    return "Farhan";
  }
}

Here, @Injectable indicates that the class can be used as an Angular service, while providedIn: 'root' makes the service available to the application.

02
Dependency Injection

Dependency Injection is the mechanism by which Angular provides a required service to a component rather than making the component create that service itself.

constructor(private studentService: StudentService) {
}

showStudent() {
  console.log(this.studentService.getStudent());
}

Working

A reusable service is created.
Angular knows that it is a service through @Injectable.
The component declares the service as a constructor dependency.
Angular provides the required StudentService object.
The component calls the service's methods when required.

Benefits

Code reuse
Less duplication
Better separation of responsibilities
Easier maintenance
Components remain cleaner because reusable logic is stored in services
ConclusionServices hold reusable functionality, while Dependency Injection provides those services to components automatically, making Angular applications more organized and maintainable.
16
5 Marks Question

Explain How to Create and Inject a Service in Angular

A service is created when reusable data or functionality needs to be shared by different components. Angular CLI can generate the service, and Dependency Injection is then used to provide it to a component.

01
Generate the Service
ng generate service student

or:

ng g service student
02
Define the Service
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class StudentService {
  getStudent() {
    return "Farhan";
  }
}
03
Understand @Injectable

@Injectable tells Angular that the class can be used as a service. With providedIn: 'root', the service is made available at the root application level.

04
Inject the Service into a Component

The component receives the service through its constructor — this is Dependency Injection.

constructor(private studentService: StudentService) {
}
05
Use the Service
showStudent() {
  console.log(this.studentService.getStudent());
}

Here, the component does not create StudentService using new. Angular provides it through dependency injection.

Flow

Angular CLI
    |
    v
StudentService
    |
    v
 @Injectable
    |
    v
Component constructor
    |
    v
Use service methods
ConclusionCreating a service centralizes reusable functionality, while injecting it through the constructor allows components to use that functionality without creating the service themselves.
17
5 Marks Question

Explain HttpClient and How it is Used to Call REST APIs

A REST API is an interface that allows an application to communicate with a server using HTTP methods such as GET, POST, PUT and DELETE. Angular provides HttpClient to make HTTP requests to REST APIs.

HTTP Methods

GET
Retrieve data.
POST
Send/create data.
PUT
Update data.
DELETE
Delete data.

Basic HttpClient Example

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

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

  constructor(private http: HttpClient) {
  }

  getStudents() {
    return this.http.get('https://example.com/students');
  }
}
HttpClient is imported from @angular/common/http.
HttpClient is injected into the service through the constructor.
getStudents() calls the server using this.http.get().
The URL identifies the REST endpoint.
The returned response can be used by the component that calls the service.

Conceptual Flow

Angular Component
        |
        v
  StudentService
        |
        v
    HttpClient
        |
        | GET / POST / PUT / DELETE
        v
   REST API / Server
        |
        v
     Response

A StudentService can call a REST endpoint such as https://example.com/students. The server can return student information, which the Angular application can then use to display a student list.

ConclusionHttpClient provides Angular applications with a standard way to communicate with servers and REST APIs using HTTP methods such as GET, POST, PUT and DELETE.