Unit 4 Stu
Unit 4 Stu
Program:-
var express = require('express');
var app = express();
app.get('/hello', function(req, res)
{ res.send("Hello World!"); });
app.listen(3000);
Methods Description
originalUrl original URL string of the
request.
protocol The protocol string, for
example, http or https.
ip Ip address of the request.
res.send('Hello World!');
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Response object:-
Methods Description
get(header) Returns the value of the
header specified
res.headersSet It is a Boolean property that
indicates if the app sent HTTP
headers for the response
set(header, value) Sets the value of the
header.
What is Angular?
Angular is a popular open-source web
application framework developed and
maintained by google.it is used for building
dynamic, single-page client applications(SPAs).
Angular is built using TypeScript.
Importance of angular:-
Angular.js is an open-source framework of
Javascript. It is written in Typescript language
and maintained by Google.
Angular is a Javascript Framework-based
development platform for building a single-page
application for mobile and desktop. It
uses Typescript & HTML to build Apps. The
Angular itself is written using Typescript.
Features of angular:-
1)Two-way data binding:-
Ensures synchronization between the
model(data) and the view (UI) .Any changes in
the data automatically reflect in the UI and vice
versa.
2. Components
Angular applications are built using components,
which are self-contained, reusable building
blocks. Each component has its own logic,
template, and styling, promoting modularity and
maintainability.
3)Dependendency injection:-
Manages and injects dependencies
(services,objects,etc)efficiently,improving code
modularity and testability
4) Pipes
Pipes in Angular transform data in templates.
Angular provides several built-in pipes for
formatting, filtering, and sorting data, and you
can create custom pipes to suit your specific
needs.
5). Testing
Angular has excellent support for testing, with
tools like Karma and Protractor for unit and end-
to-end testing, respectively. It encourages
writing tests alongside code, ensuring
application reliability and maintainability.
6. Routing
Angular's built-in router allows you to build
single-page applications with multiple views. It
provides features like nested routes, lazy loading,
route guards, and parameterized routes,
enabling complex navigation scenarios.
7. Services
Services in Angular are single instance objects
that are used to organize and share code across
components. They encapsulate reusable
functionality such as data fetching,
authentication, and business logic.
8)built-in routing:-
The @angular/router module helps manage
navigation and transitions between different
application views seamlessly.
Angular Components:-
Angular components are the building blocks of
Angular applications. They encapsulate a part of the
user interface, including its template, styles, and
behavior. Each component represents a reusable
piece of UI functionality and can be composed
together to create complex applications.
Components in Angular follow the principles of
encapsulation, reusability, and maintainability,
making them essential in Angular development.
Component Structure:-
The structure of an Angular component consists of
main parts:
selector: This option allows you to define
the HTML tag name used to add the
component to the application via HTML.
app.component.ts
import {Component} from'@angular/core';
@Component({
selector: 'message',
template: `
<h1>Hello World!</h1>`,
})
export class Chap3Component
{
title = 'My First Angular App';
}
Adding Angular to Your 39
Environment 3
Output:-
Expressions:-
Expressions in AngularJS are used to bind application
data to HTML. The expressions are resolved by
AngularJS and the result is returned back to where the
expression is written. The expressions in AngularJS are
written in double braces: {{ expression }}. They behave
similar to ng-bind directives: ng-bind=”expression”.
Syntax:
{{ expression }}
Program:-
<!DOCTYPE html>
<html>
Adding Angular to Your 39
Environment 3
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.
6.9/angular.min.js"></script>
<body>
<div ng-app>
<p>My first expression: {{ 5 + 5 }}</p>
</div>
</body>
</html>
Data binding
Data Binding is a way to synchronize the data
between the model and view components
automatically. AngularJS implements data-binding
that treats the model as the single-source-of-truth
in your application & for all the time, the view is a
projection of the model.
Types of data binding
There are basically two approaches used for data
bindings
1)one way binding
Adding Angular to Your 39
Environment 3
1)interpolation binding:-
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
val: string = 'helloworld';
}
Adding Angular to Your 39
Environment 3
2)property binding:-
Similar to Java, variables defined in the parent
class can be inherited by the child class which is
templates in this case. The only difference between
Interpolation and Property binding is that we
should not store non-string values in variables
while using interpolation. So if we have to store
Boolean or other data types then use Property
Binding. In simple words, we bind a property of a
DOM element to a field which is a defined property
in our component TypeScript code.
Syntax:
[class]="variable_name"
Program:-
import {Component} from '@angular/core';
@Component({
selector: 'app-root',
styleUrls: ['app.component.css'],
template: `
<h2>Welcome {{ name }}</h2>
<input [contentEditable]="isEditable" type="text"
value="john" />
Adding Angular to Your 39
Environment 3
`,
export class AppComponent {
isEditable = true;
}
Program:-
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet],
template: '
Adding Angular to Your 39
Environment 3
background-color: blue;
}
.redText{
color: red;
font-size: 24px;
}
`]
})
export class AppComponent {
myCustomClass: string = 'blueBox';
isTrue =true;
}
6)Event binding:-
Event binding is used to handle the events raised by
the user actions like button click, mouse movement,
keystrokes, etc.
Using Event Binding we can bind data from DOM to the component and
hence can use that data for further purposes.
Syntax:
< element (event) = function() >
app.component.html
<h1>
Welcome to lab
</h1>
<input (click)="gfg($event)" value="hello">
app.component.ts
app.component.html:-
<div >
<h3>Two-way Data Binding</h3>
<input type="text"
placeholder="Enter text"
[(ngModel)]="val" />
<br />
{{ val }}
</div>
app.component.ts:-
import { Component } from "@angular/core";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
Adding Angular to Your 39
Environment 3
styleUrls: [],
})
export class AppComponent {
val: string;
}
Built in directives:-
Directives are JavaScript classes with metadata
that defines the structure and behavior.
Directives provide the majority of UI
functionality for Angular applications.
1)ngIf
The ng-if Directive in AngularJS is used to remove or
recreate a portion of the HTML element based on an
expression. The ng-if is different from the ng-hide
directive because it completely removes the element in
the DOM rather than just hiding the display of the
element. If the expression inside it is false then the
element is removed and if it is true then the element is
added to the DOM.
Syntax:-
<div *ngif=”condition”>content to display when
condition is true<?div>
Program1
Adding Angular to Your 39
Environment 3
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.
6.9/angular.min.js"></script>
<body ng-app="">
<div ng-if="myVar">
<h1>Welcome</h1>
<p>Welcome to my home.</p>
<hr>
</div>
</body>
</html>
ngFor
NgFor is used as a structural directive that renders each
element for the given collection each element can be
displayed on the page.
Syntax:-
<li *ngFor='condition'></li>
Program-1
app.component.html
<ul>
<li *ngFor='let i of a'> {{i}} </li>
</ul>
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
})
Adding Angular to Your 39
Environment 3
ngSwitch
The ng-switch Directive in AngularJS is used to specify the
condition to show/hide the child elements in HTML DOM.
The HTML element will be displayed only if the expression
inside the ng-switch directive returns true otherwise it will be
hidden. It is supported by all HTML elements.
Program-1
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular
.min.js"></script>
<body ng-app="">
<select ng-model="myVar">
<option value="dogs">Dogs
<option value="tuts">Tutorials
<option value="cars">Cars
</select>
<hr>
<div ng-switch="myVar">
<div ng-switch-when="dogs">
<h1>Dogs</h1>
<p>Welcome to a world of dogs.</p>
</div>
<div ng-switch-when="tuts">
<h1>Tutorials</h1>
<p>Learn from examples.</p>
</div>
<div ng-switch-when="cars">
<h1>Cars</h1>
<p>Read about cars.</p>
</div>
<div ng-switch-default>
<h1>Switch</h1>
<p>Select topic from the dropdown, to switch the content of
this DIV.</p>
Adding Angular to Your 39
Environment 3
</div>
</div>
<hr>
</body>
</html>
3)Attribute: Attribute directives are a powerful
tool that allows you to manipulate the behavior
and appearance of HTML elements.
Program
app.module.ts:-
Adding Angular to Your 39
Environment 3
app.component.html
<app-my-form></app-my-form>
app.my-form.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-my-form',
templateUrl: './my-form.component.html',
styleUrls: [],
})
export class MyFormComponent {
user = {
name: '',
email: ''
};
submitted = false;
onSubmit() {
this.submitted = true;
console.log('Form submitted', this.user);
Adding Angular to Your 39
Environment 3
onFocus() {
console.log('Input focused');
}
onBlur() {
console.log('Input blurred');
}
}
app.my-form.component.html
<div class="form-container">
<form (ngSubmit)="onSubmit()"
#userForm="ngForm">
<label for="name">Name:</label>
<input type="text" id="name name="name"
required
[(ngModel)]="user.name"
(focus)="onFocus()"
(blur)="onBlur()"
Adding Angular to Your 39
Environment 3
/>
<label for="email">Email:</label>
<input
type="email"
id="email"
name="email"
required
[(ngModel)]="user.email"
/>
<button type="submit">Submit</button>
</form>
Output:-
Adding Angular to Your 39
Environment 3
Custom directives
We can also create our own directives based on our
own requirements. This helps us creating reusable
components and validating data etc. We can also create
our own directives based on our own requirements.
This helps us creating reusable components and
validating data etc. Custom directives can be created
using the `@Directive` decorator and can implement
various methods to interact with the host element and
perform actions.
<form>
<div>
<label>Name: </label>
Adding Angular to Your 39
Environment 3
<input
appUpperCase
type="text"
name="name"
minlength="4"
[(ngModel)]="name"
#nameInput="ngModel"
required
[ngClass]="{ 'is-invalid': nameInput.touched &&
nameInput.invalid }"
/>
<div *ngIf="nameInput.touched &&
nameInput.invalid">
Minimum length of name is 4 characters
</div>
</div>
<div>
<label>Age: </label>
<input
type="number"
name="age"
Adding Angular to Your 39
Environment 3
[(ngModel)]="age"
#ageInput="ngModel"
required
[ngStyle]="{
'border-color': ageInput.invalid &&
ageInput.touched ? 'red' : ''
}"
/>
<div *ngIf="ageInput.touched &&
ageInput.invalid">Age is required</div>
</div>
</form>
Service Description
animate Provides animation hooks to link into both CSS- and JavaScript-based animations
http Provides a simple-to-use functionality to send HTTP requests to the web server or other
service
router Provides navigation between views and between sections within views
forms Provides a service that allows for dynamic and reactive forms with simple form
validation
employee.json
{
"name": "John Doe",
"position": "Software Engineer",
"department": "IT"
}
(index.html)
<!DOCTYPE html>
<html>
<head>
<title>Employee Info</title>
Adding Angular to Your 39
Environment 3
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.
6.9/angular.min.js"></script>
</head>
<body ng-app="myApp"
ng-controller="EmployeeController">
<h2>Employee Information</h2>
<p><strong>Name:</strong> {{employee.name}}</p>
<p><strong>Position:</strong>
{{employee.position}}</p>
<p><strong>Department:</strong>
{{employee.department}}</p>
<script>
var app = angular.module('myApp', []);
app.controller('EmployeeController', function($scope, $http)
$http.get('employee.json') .then(function(response) {
$scope.employee = response.data;
});
});
</script>
Adding Angular to Your 39
Environment 3
</body>
</html>