Unit I - Notes
Unit I - Notes
WEB FRAMEWORKS
CS2404 3 0 2 4
Course Objectives:
UNIT I – ANGULAR V 12 9
Angular Modules – HTTP client, Forms Module – Angular Service Files – Dependancy Injection –
Angular Material – Connecting Angular with Back End
UNIT III – REACT V 18 9
Introduction to React – Setting development environment – create app – JSX syntax – properties and
states – components – React routing – API request
UNIT IV – REACT HOOKS 9
Introduction to Image and Container – Docker – Containers – Docker Images, Docker file, Docker
Network – Docker Compose - Kubernetes
45 PERIODS
COURSE OUTCOMES:
TEXT BOOKS:
1. Nate Murray, Felipe Coury, Ari Lerner, Carlos Taborda, “ The Ng book — The Complete Book
on Angular”
2. The Road to React, Robin Wieruch,2023.
3. The Docker Book: Containerization is the new virtualization, James Turnbull, 2014.
4. The Kubernetes Book, Nigel Poulton, 2023.
ONLINE RESOURCES:
1. https://angular.io/docs
2. https://react.dev/
3. https://react.dev/reference/react
4. https://docs.docker.com/
5. https://kubernetes.io/docs/home/
Introduction to Angular & Angular CLI
Installation
With node.js and npm installed, the next step is to install the Angular CLI which provides
tooling for effective Angular development.
From a Terminal window run the following command: npm install -g @angular/cli.
Develop applications in the context of an Angular workspace. A workspace contains the files
for one or more projects. A project is the set of files that make up an application or a library.
1. Ensure that you aren't already in an Angular workspace directory. For example, if
you're in the Getting Started workspace from an earlier exercise, navigate to its
parent.
2. Run ng new followed by the application name as shown here:
ng new angular-tour-of-heroes
3. ng new prompts you for information about features to include in the initial project.
Accept the defaults by pressing the Enter or Return key.
ng new installs the necessary npm packages and other dependencies that Angular requires.
This can take a few minutes.
ng new also creates the following workspace and starter project files:
The initial application project contains a simple application that's ready to run.
cd angular-tour-of-heroes
ng serve --open
https://angular.io/tutorial/first-app/first-app-lesson-01
Components
Components are the main building blocks for Angular applications. Each component consists
of:
To create a component, verify that you have met the following prerequisites:
In this step, you add the new component, HomeComponent to your app's root
component, AppComponent, so that it displays in your app's layout.
imports: [
HomeComponent,
],
Data binding allows Internet users to manipulate web page elements with the help of a web
browser. It includes dynamic HTML and does not require complex programming. Data
binding is used in web applications that contain interactive components such as forms,
calculators, tutorials, and games. The incremental display of a webpage makes data binding
convenient when pages contain an extensive amount of data.
Angular uses the concept of two-way binding. Any UI element-related change is reflected in
the corresponding and specific model state. Conversely, any model state changes reflect in
the UI state. This ensures that the framework is able to connect the DOM to the Model data
with the help of the controller.
Attribute Binding
Attribute binding in Angular helps you bind to HTML attributes of elements in your
template. This can be useful when you want to dynamically update the appearance or
behavior of an element based on some condition. For example, you might want to hide an
element unless a user is logged in, or change the color of an element based on its status. To
bind to an attribute, you use the square brackets around the attribute name.
Class Binding
Angular offers various ways to bind data to HTML elements. Class binding is one of them. It
allows you to dynamically add or remove CSS classes from an element. This can be useful
for applying styles based on certain conditions.
Style Binding
Style binding is a one-way data binding technique that can be used to set the value of a CSS
property on an element. To use style binding, you first need to have a CSS property that you
want to bind to an element.
ngModel
Angular data binding is a two-way process: it can both send and receive data. This means that
when you change something in your view, the model updates automatically, and vice versa.
The ngModel directive makes this two-way data binding possible.
When you use the ngModel directive, you specify a property of the scope as the value of the
directive. This tells Angular to create a two-way binding between the property and the input
control. Any changes to the control are automatically reflected in the model, and any changes
to the model are automatically reflected in the control.
Interpolation Binding
Interpolation is a procedure that allows the user to bind a value to the user interface element.
Interpolation binds the data one-way, which means that data moves in one direction from the
components to HTML elements.
Property Binding
Property binding is a one-way data binding mechanism that allows you to set the properties
for HTML elements. It involves updating a property value in the component and binding the
value to an HTML element in the same view. We use property binding for toggle
functionality and sharing data between components. It uses the "[]" syntax for data binding.
In the app.component.ts file, another property is created called image and provided the path
to the Logo in the assets folder.
public image = "/assets/Logo.png"
In the app.component.html file.
<img [src] = "image" alt="" style="height: 100px; width: 250px" class="center">
Event Binding
Event binding type is when information flows from the view to the component when an event
is triggered. The event could be a mouse click or keypress. The view sends the data to update
the component. Unsurprisingly, it is the exact opposite of property binding, where the data
goes from the component to the view.
We have created a Subscribe button that displays a “Thank you” message when clicked on.
<br><button (click)="onClick()">Subscribe to Simplilearn</button></div>
To display the message on the console, we’ve created a function called onClick() in the
app.component.ts file.
onClick(){
console.log("Thanks for subscribing")
}
Every time the user clicks on the button, the message is displayed on the console.
Two-way Data Binding
As the name suggests, two-way binding is a mechanism where data flows from the
component to the view and back. This binding ensures that the component and view are
always in sync. Any changes made on either end are immediately reflected on both. The
general syntax to denote two-way data binding is a combination of Square brackets and
parentheses "[()]".
To illustrate two-way data binding, we’ve created a property with an empty string and an
input box for the user to type. Whatever the user provides is displayed on the screen with the
help of the property.
In the .ts file,
public random = ""
In the .html file, we’ve created an input field
<input [(ngModel)]="random" type="text"> <br>
{{random}}
We have used the ngModel directive and initialized it to random. We’ve then interpolated the
property random.
If we run this code, an error would occur in the console - saying that the ngModel is an
unknown property of the input element. This is due to the fact, that in order to use
the ngModel directive, it's necessary to import the FormsModule. It needs to be imported into
the app.module.ts file:
import { FormsModule } from '@angular/forms';
...
@NgModule({
imports: [
BrowserModule,
FormsModule
]
...
ROUTING ON ANGULAR
In a Single Page Application (SPA), all of our application's functions exist in a single HTML
page. As users access our application's features, the browser needs to render only the parts
that matter to the user, instead of loading a new page. This pattern can significantly improve
your application's user experience.
To define how users navigate through our application, we use routes. Add routes to define
how users navigate from one part of our application to another. We can also configure routes
to guard against unexpected or unauthorized behavior.
Create a sample application
Using the Angular CLI, create a new application, angular-router-sample. This application
will have two components: crisis-list and heroes-list.
1. Create a new Angular project, angular-router-sample.
ng new angular-router-sample
1. When prompted with Would you like to add Angular routing?, select N.
When prompted with Which stylesheet format would you like to use?, select CSS.
After a few moments, a new project, angular-router-sample, is ready.
2. From your terminal, navigate to the angular-router-sample directory.
3. Create a component, crisis-list.
ng generate component crisis-list
4. In your code editor, locate the file, crisis-list.component.html and replace the
placeholder content with the following HTML.
<h3>CRISIS CENTER</h3>
<p>Get your crisis here</p>
5. Create a second component, heroes-list.
ng generate component heroes-list
6. In your code editor, locate the file, heroes-list.component.html and replace the
placeholder content with the following HTML.
<h3>HEROES</h3>
<p>Get your heroes here</p>
7. In your code editor, open the file, app.component.html and replace its contents with
the following HTML.
<h1>Angular Router Sample</h1>
<app-crisis-list></app-crisis-list>
<app-heroes-list></app-heroes-list>
8. Verify that your new application runs as expected by running the ng serve command.
ng serve
9. Open a browser to http://localhost:4200.
You should see a single web page, consisting of a title and the HTML of your two
components.
Define your routes
The route /crisis-center opens the crisis-center component.
The route /heroes-list opens the heroes-list component.
A route definition is a JavaScript object. Each route typically has two properties. The first
property, path, is a string that specifies the URL path for the route. The second
property, component, is a string that specifies what component your application should
display for that path.
1. From your code editor, create and open the app.routes.ts file.
2. Create and export a routes list for your application:
import {Routes} from '@angular/router';
PROPERTIE
DETAILS
S
match. For this tutorial, you should set this property to full. This
strategy is recommended when you have an empty string for a
path.
Now when you open your application, it displays the heroes-list component by
default.
DIRECTIVE
DETAILS
TYPES
Attribute directives listen to and modify the behavior of other HTML elements, attributes,
properties, and components.
This section is used to create a highlight directive that sets the background color of the host
element to yellow.
@Directive({
standalone: true,
selector: '[appHighlight]',
})
export class HighlightDirective {
constructor(private el: ElementRef) {
this.el.nativeElement.style.backgroundColor = 'yellow';
}
}
Applying an attribute directive
To use the HighlightDirective, add a <p> element to the HTML template with the directive as
an attribute.
<p appHighlight>Highlight me!</p>
Angular creates an instance of the HighlightDirective class and injects a reference to
the <p> element into the directive's constructor, which sets the <p> element's background
style to yellow.
Handling user events
This section shows you how to detect when a user mouses into or out of the element and to
respond by setting or clearing the highlight color.
In src/app/highlight.directive.ts (imports)
import {Directive, ElementRef, HostListener} from '@angular/core';
2. Add two event handlers that respond when the mouse enters or leaves, each with
the @HostListener() decorator.
@HostListener('mouseenter') onMouseEnter() {
this.highlight('yellow');
}
@HostListener('mouseleave') onMouseLeave() {
this.highlight('');
}
Structural directives
ngIf
<ng-template #elseBlock>
<!-- Content to display when condition is false -->
<p>This content is displayed when the condition is false.</p>
</ng-template>
In this example:
</div>
<ng-template #firstName>
<h2>Sutha</h2>
</ng-template>
<ng-template #lastName>
<h2>Balakumar</h2>
</ng-template>
ngSwitch
<div [ngSwitch]="expression">
<div *ngSwitchCase="value1">Content for value1</div>
<div *ngSwitchCase="value2">Content for value2</div>
<!-- Add more ngSwitchCase as needed -->
<div *ngSwitchDefault>Default content if no match</div>
</div>
Example:
<div [ngSwitch]="status">
<div *ngSwitchCase="'active'">Status is Active</div>
<div *ngSwitchCase="'inactive'">Status is Inactive</div>
<div *ngSwitchCase="'pending'">Status is Pending</div>
<div *ngSwitchDefault>Unknown Status</div>
</div>
Here, assuming status is a variable in your component, the content inside
the appropriate *ngSwitchCase block will be displayed based on the value
of status.
ngFor
In Angular, the ngFor directive is used for rendering a set of elements for
each item in an iterable list. It allows you to iterate over a collection (such
as an array or an object) and generate HTML content for each item.
we have an array of fruits in an Angular component, and we want to use
the ngFor directive to iterate over the array and display each fruit in a list.
// fruit-list.component.ts
@Component({
selector: 'app-fruit-list',
})
export class FruitListComponent {
fruits = ['Apple', 'Banana', 'Orange', 'Mango'];
}
<h2>Fruit List</h2>
<ul>
<li *ngFor="let fruit of fruits">{{ fruit }}</li>
</ul>
Typescript Vs Javascript
TypeScript and JavaScript are both programming languages, but they
have some key differences:
1. Static Typing:
JavaScript: It is a dynamically typed language, meaning you
don't have to explicitly declare the data type of a variable.
The type of a variable can change during runtime.
TypeScript: It is a statically typed superset of JavaScript,
which means that you can declare the type of a variable at
compile-time. TypeScript introduces static typing, providing a
way to catch errors during development.
2. Compilation:
JavaScript: It is an interpreted language that is executed by
the browser or another JavaScript runtime environment.
TypeScript: It needs to be transpiled into JavaScript before
execution. TypeScript code is written in a higher level of
abstraction and is compiled to JavaScript.
3. Object-Oriented Features:
JavaScript: It is prototype-based and supports object-
oriented programming using prototypes and constructor
functions.
TypeScript: It is designed with optional static typing and
includes features such as classes, interfaces, modules, and
other constructs commonly found in object-oriented
languages.
4. Tooling and IDE Support:
JavaScript: It has good tooling and support in various IDEs
(Integrated Development Environments) and text editors.
TypeScript: Because of its static typing, TypeScript provides
better tooling support. Features like autocompletion, code
navigation, and error checking are more robust in TypeScript.
5. Compatibility:
JavaScript: Code written in JavaScript is compatible with all
major browsers and environments that support ECMAScript
standards.
TypeScript: TypeScript code needs to be transpiled to
JavaScript, and the resulting JavaScript code is compatible
with any environment that supports ECMAScript standards.
6. Null and Undefined:
JavaScript: Variables can be null or undefined .
TypeScript: With strict null checks enabled, TypeScript
introduces a type null and undefined that can be explicitly
assigned to variables.
7. Enums:
JavaScript: Does not have built-in support for enums.
TypeScript: Supports enums, making it easier to work with a
set of named constants.
8. Modules:
JavaScript: Uses a variety of module systems, including
CommonJS and AMD, but does not have built-in support for
modules until the introduction of ECMAScript modules (ES6).
TypeScript: Supports ECMAScript modules as well as its own
module system, making it easier to organize and reuse code.
Named Parameters
Typing named parameters follows the same pattern as typing normal parameters.
Example
function divide({ dividend, divisor }: { dividend: number, divisor: number }) {
return dividend / divisor;
}
Rest Parameters
Rest parameters can be typed like normal parameters, but the type must be an array as rest
parameters are always arrays.
Example
function add(a: number, b: number, ...rest: number[]) {
return a + b + rest.reduce((p, c) => p + c, 0);
}
Type Alias
Function types can be specified separately from functions with type aliases.
Example
type Negate = (value: number) => number;
// in this function, the parameter `value` automatically gets assigned the type `number` from
the type `Negate`
const negateFunction: Negate = (value) => value * -1;
TypeScript Classes
TypeScript adds types and visibility modifiers to JavaScript classes.
Members: Types
The members of a class (properties & methods) are typed using type annotations, similar to
variables.
Example
class Person {
name: string;
}
Override
When a class extends another class, it can replace the members of the parent class with the
same name.
Newer versions of TypeScript allow explicitly marking this with the override keyword.
Example
interface Shape {
getArea: () => number;
}
By default the override keyword is optional when overriding a method, and only helps to
prevent accidentally overriding a method that does not exist. Use the
setting noImplicitOverride to force it to be used when overriding.
Abstract Classes
Classes can be written in a way that allows them to be used as a base class for other classes
without having to implement all the members. This is done by using the abstract keyword.
Members that are left unimplemented also use the abstract keyword.
Example
abstract class Polygon {
public abstract getArea(): number;
Abstract classes cannot be directly instantiated, as they do not have all their members
implemented.