0% found this document useful (0 votes)
9 views49 pages

Unit 4 Stu

The document provides an overview of Express.js and Angular, detailing their features, installation processes, and basic usage. Express.js is a flexible Node.js framework for building web applications, while Angular is a TypeScript-based framework for creating dynamic single-page applications. Key concepts such as routing, middleware, data binding, and component structure are discussed for both technologies.

Uploaded by

viickyy0011
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views49 pages

Unit 4 Stu

The document provides an overview of Express.js and Angular, detailing their features, installation processes, and basic usage. Express.js is a flexible Node.js framework for building web applications, while Angular is a TypeScript-based framework for creating dynamic single-page applications. Key concepts such as routing, middleware, data binding, and component structure are discussed for both technologies.

Uploaded by

viickyy0011
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 49

Unit-4

Getting started with express


Express.js is a minimal and flexible Node.js web
application framework that provides a list of
features for building web and mobile
applications easily. It simplifies the development
of server-side applications by offering an easy-to-
use API for routing, middleware, and HTTP
utilities.
 Built on Node.js for fast and scalable server-
side development.
 Simplifies routing and middleware handling
for web applications.
 Supports building REST APIs, real-time
applications, and single-page applications.
 Provides a lightweight structure for flexible
and efficient server-side development.
Features of Express:-
 Routing:
Express.js provides a simple and flexible
routing system that allows developers
to map HTTP requests to specific functions.
 Templates:
Express.js provides a variety of template
engines that can be used to render HTML
pages. It supports popular template engines
like EJS, Handlebars, and Pug.
 Error Handling:
Express.js provides robust error handling
features that help developers handle errors
and exceptions in their applications.
 Security:
Express.js provides built-in security features
like Helmet, which helps protect against
common security vulnerabilities like cross-
site scripting (XSS) and cross-site request
forgery (CSRF).
 Easy to Use:
Express.js is easy to use and requires
minimal configuration, making it ideal for
developers who want to build web
applications quickly.
Installing Express:-
Express is installed using node package
manager(npm).The command issued for
installing the express js.
npm install express

creating instance of express


create an instance of the express class. This
instance acts as the HTTP server for the Node.js
application .
following lines create an instance of express
var express=require(‘express’)
var app=express()

Program:-
var express = require('express');
var app = express();
app.get('/hello', function(req, res)
{ res.send("Hello World!"); });
app.listen(3000);

using request and response object:-


Both the objects 'req' and 'res' are responsible
for handling the HTTP requests and responses in
the web applications.
Request object:-
The route handlers are passed a Request object as
the first parameter. The Request object provides
the data and metadata about the request, including the
URL, headers, query string, and much more. This
allows you to handle the request appropriately in
your code.
lists some of the more commonly used properties
available in the Request object.

Methods Description
originalUrl original URL string of the
request.
protocol The protocol string, for
example, http or https.
ip Ip address of the request.

path Path portion of the request


URL
hostname Hostname of the
request.

get(header) Returns the value of the


header.

query Query string portion of the


request URL.

method HTTP method. GET, POST,


etc.
stale A Boolean that is false
when last-modified
matches.

const express = require('express');


const app = express();
const PORT = 3000;
app.get('/', (req, res) => {
console.log('Request URL:', req.url);
console.log('Request Method:', req.method);

console.log('Request Headers:', req.headers);

res.send('Hello World!');
});

app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Response object:-

The Response object passed to the route


handler provides the necessary functionality to
build and send a proper HTTP response. The
following sections discuss using the Response
object to set headers, set the status, and send
data back to the client.

lists some of the more commonly used properties


available in the Request 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.

set(headerObj) Accepts an object that contains


multiple 'header':'value'
properties. Each of the
headers in the headerObj is set
in the response obj

location(path) Set the location header to path


specified the path can be a
URL path such as /login, a full
URL such as http://
server.net/, a relative path
such as ../users, or a browser
type(type_string) Sets the Content-Type header
based on the type_string
parameter The type_string
parameter can be a normal con-
tent type such as
application/json, a partial type
such as png, or it can be a file
extension such as .html.
attachment([filepath]) Sets the Content-
Disposition header to
attachment, and if a
filepath is specified the
Content-Type header is set
based on the file extension.

var express =require('express');


var url = require('url');
var app =express();
app.listen(80);
app.get('/', function (req, res) {
var response = '<html><head><title>Simple
Send</title></head>' + '<body><h1>Hello from
Express</h1></body></html>';
res.status(200);
res.set({'Content-Type': 'text/html','Content-Length':
response.length });
res.send(response);
console.log('Response Finished? ' + res.finished);
console.log('\nHeaders Sent: ');
console.log(res.headerSent); });
app.get('/error', function (req, res) {
res.status(400);
res.send("This is a bad request."); });

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.

 Template: The template defines the HTML


markup of the component's view. It contains
placeholders and Angular directives that are
replaced with dynamic data and logic during
runtime.
 templateUrl: This option allows you to
import an external template file rather
than inline HTML. This is helpful for
separating a large amount of HTML code
out of a component to help with
maintainability.

 Styles: The styles define the component's visual


appearance, including CSS rules and stylesheets.
Styles can be defined using inline styles, external
CSS files, or CSS preprocessors like Sass or Less.
 viewProviders: This is an array of
dependency injection providers. It allows
you to import and use Angular services
that provide application functionality
such as HTTP communications.
 TypeScript Code: The TypeScript code defines
the component's behavior and logic. It includes
properties, methods, and lifecycle hooks that
control how the component interacts with the
DOM, handles user input, and responds to
changes in its state or props.
Example:-

import {Component} from


'@angular/core';
@Component({
selector: 'my-app',
template: '<p>My Component</p>'
})
export class AppComponent{
Title = 'Chapter 1 Example';
}

Using the Angular CLI:-


Angular provides a powerful CLI that makes
building out Angular applications a much
more streamlined process. By using the CLI,
you will quickly be able to generate new
Angular applications, components, directives,
pipes, and services. The following sections go
over some of the most important tools
available through the CLI.

Generating Content with the CLI:-


One of the most common purposes of the CLI is to
generate content for applications. It automates the
process of creating and bootstrapping a new Angular
application, letting you get straight to the meat of the
application.
From the command line, run the command ng new
[application name] to create a new Angular
application. If you navigate to that newly created
application, you have access to many other useful
commands. Table 21.1 lists some of the most
important commands that the CLI has to offer.

Table 21.1 Angular CLI Command Options


Command Alias Purpos
e
ng new Creates a new
Angular application
ng serve Builds and runs the
angular application for
testing
ng eject Makes the webpack
config files available to
be edited
ng generate component [name] ng g c [name] Creates a new
component
ng generate directive [name] ng g d [name] Creates a new directive
ng generate module [name] ng g m [name] Creates a module
ng generate pipe [name] ng g p [name] Creates a pipe
ng generate service [name] ng g s [name] Creates a service
ng generate enum [name] ng g e [name] Creates an enumeration
ng generate guard [name] ng g g [name] Creates a guard
ng generate interface [name] ng g i [name] Creates an interface

Creating a Basic Angular Application:-


Now that you understand the basics of the Angular
CLI, you are ready to get started implementing
Angular code. This section walks you through a very
basic Angular application that implements an
Angular component with an inline template, an inline
stylesheet, and the Component class.
For this example, it is expected that you have started
working through the Angular QuickStart guide and
understand the basics of the CLI. The first thing to do is
to create a directory where you can place your
projects.
When you have your directory set up, the next step is
to generate your first Angular application. Run the
following command to create the application for this
example:
1) Install the Angular CLI.
npm install -g @angular/cli
2) Creating a basic angular application
ng new first
3) run project
ng serve

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

2)two way binding

One-way Binding: This type of binding is unidirectional, i.e.


this binds the data flow from either component to
view(DOM) or from the view(DOM) to the component. There
are various techniques through which the data flow can be
bind from component to view or vice-versa

1)interpolation binding:-

Angular interpolation is used to display a component


property in the respective view template with double
curly braces syntax. Interpolation is used to transfer
properties mentioned in the component class to be
reflected in its template.
Syntax: {{ variable_name }}
Program:-
app.component.html
<h3>Binding Types</h3>
<p>Interpolation</p>
<br>
<h5>
Adding Angular to Your 39
Environment 3

Addition of 3 and 5 with


Interpolation is {{3+5}}
</h5>
<h5>
Addition of 3 and 5 without
Interpolation is 3+5
</h5>
<h2>{{val}}</h2>

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

3)Attribute binding: This type of binding allows


the setting of attributes to an HTML element.
It is a technique that allows the user to bind
attributes of elements from component to view
(template)
Syntax:-
[att.attribute_name]=”expression”

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

<div [attr.aria-label] = "labelName"></div>


styleUrl: './app.component.css'
})
export class AppComponent {
title = 'first-app';
labelName = test;
}

4)Class binding: You can use this type of binding


to set CSS class names to the element.

//Program to apply class binding for single class

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


@Component({
selector: 'app-root',
template: `
<div [class]="myCustomClass"></div>
<span [class.redText]="isTrue">Hello my blue friend</span> `,
styles: [`
.blueBox {
height: 150px;
width: 150px;
Adding Angular to Your 39
Environment 3

background-color: blue;
}
.redText{
color: red;
font-size: 24px;
}
`]
})
export class AppComponent {
myCustomClass: string = 'blueBox';
isTrue =true;
}

5)Style binding: You can use this type of


binding to create inline CSS styles for the
element.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<span [style.border]="myBorder">Hey there</span>
<div [style.color]="twoColors ? 'blue' : 'forestgreen'">
</div>
<button (click)="changeColor()">click me</button>`
})
export class AppComponent {
twoColors: boolean = true;
changeColor = function(){
this.twoColors = !this.twoColors; }
myBorder = "1px solid black";
}
Adding Angular to Your 39
Environment 3

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

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


@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
gfg(event) {
console.log(event.toElement.value);
}
}
Adding Angular to Your 39
Environment 3

2)Two way binding


Two way binding is a technique in which we can pass
the data from view(templete) to component and from
component to view.

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.

There are three major types of directives:


1)Components: A component directive is a
directive that incorporates an HTML template
with JavaScript functionality to create a self-
contained UI element that can be added
to an Angular application as a custom HTML
element. Components are likely to be the
directives you use the most in Angular.
Adding Angular to Your 39
Environment 3

2)Structural: You use structural directives when


you need to manipulate the DOM. Structural
directives allow you to create and destroy
elements and components from a view.
There are three most popularly used structural
directive:-
1)ngIf 2)ngFor 3)ngSwitch

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="">

Keep HTML: <input type="checkbox" ng-


model="myVar" ng-init="myVar = true">

<div ng-if="myVar">
<h1>Welcome</h1>
<p>Welcome to my home.</p>
<hr>
</div>

<p>The DIV element will be removed when the


checkbox is not checked.</p>
<p>The DIV element will return, if you check the
checkbox.</p>
Adding Angular to Your 39
Environment 3

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

export class AppComponent {


a=['gfg1', 'gfg2', 'gfg3', 'gfg4']
}

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="">

My favorite topic is:


Adding Angular to Your 39
Environment 3

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

<p>The ng-switch directive hides and shows HTML sections


depending on a certain value.</p>

</body>
</html>
3)Attribute: Attribute directives are a powerful
tool that allows you to manipulate the behavior
and appearance of HTML elements.

Types of Attribute Directives:


We have 3 main built in attribute directives: ngClass,
ngStyle and ngModel
1. ngClass
This attribute is used to conditionally give the classes to
the elements based on the value binded to ngClass
directive.
Syntax:
<element [ngClass]="expression"></element>
2. ngStyle
Adding Angular to Your 39
Environment 3

This attribute is used to dynamically apply the styles to


elements based on the value binded to ngStyle
directive. It helps us to modify the appearance of
elements on conditional basis. We can also use
ngStyles to override in
Syntax:
<element [ngStyle]="expression"></element>
3. ngModel
This attribute is generally used to bind form control
data to a class variable . This allows a two way binding
and this is most commonly used directive with forms. It
also comes with few basic validations like
required,minLength , maxLength which can be directly
used in our input tags.
To use this directive we need to import Forms Module
in our module file.
Syntax:
<input name="name" [(ngModel)]="name"/>

Program
app.module.ts:-
Adding Angular to Your 39
Environment 3

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


import { BrowserModule } from '@angular/platform-
browser';
import { FormsModule } from '@angular/forms'
import { AppComponent } from './app.component';
import { MyFormComponent } from './my-form/my-
form.component';
@NgModule({
declarations: [
AppComponent,
MyFormComponent
],
imports: [
BrowserModule,
FormsModule // Add this here too!
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
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>

<div *ngIf="submitted" class="confirmation">


Form submitted! Hello, {{ user.name }}.
</div>
</div>

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.

There are two types of directives:


1.Attribute Directives
2.Structural Directives
Adding Angular to Your 39
Environment 3

Steps to create Custom Directives:


Step 1: Create a Directive
ng generate directive <directive-name>
The above command helps us to create new directive.
Step 2: Implement necessary imports
Open the generated directive file and import necessary
modules like ElementRef , HostListener etc.
ElementRef : Provides access to the respective DOM
element to change the styles or properties .
HostListener : Decorator used to listen for events on
the host element such as mouse controls , clicks etc.
Input (optional) : Allows you to pass data from the
component template to the directive.
import {Directive, ElementRef, HostListener , Input }
from '@angular/core';
Step 3: Define the Selector
Adding Angular to Your 39
Environment 3

In the @Directive decorator , we need to provide the


`selector` property to specify how the directive will be
used in the template. If we use the ng generate
directive command, it gives selector property by
default, we can also change this selector name for our
usage.
@Directive({
selector: '[appHighlight]'
}
Step 4: Implement the logic
Here, we can write our custom functionality in the
directive file. We can also implement life cycle hook
methods in the directive file if required. Here we can
also pass inputs to the directive
using @Input decorator.
Step 5: Using our directive in template
In our component's template, we can use the selector
given in the directive as an attribute to the required
element on which we want to perform our logic.
<element appNewDirective>.....content </element>
Here appNewDirective is the selector of our directive.
In this way we can use the directive in our component
templates with the custom functionality.
Adding Angular to Your 39
Environment 3

As mentioned above, we can also pass inputs to


directive.
<element appNewDirective
[input1]="value">.....content </element>
In this way we can pass inputs to our custom directive,
here input1 is the input we declared as @Input() in our
decorative, and `value` is the data we are passing to
that particular input. Based on our requirement we can
pass multiple inputs .
Example of Attribute Directives:
Now let us take an example to understand both built-in
attribute directives and also custom directives.
Step 1: Create a new angular project
ng new project
Step 2. To generate a new directive, we can use the
following command.
ng generate directive upperCase
<!-- app.component.html -->

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

Implementing angular services in web application

The purpose of a service is to provide a concise bit of code


that performs specific tasks.

Using the Built-in Services


Angular provides several built-in services that are
included in the Angular module,
some of the most common built-in angular services
are:-
Adding Angular to Your 39
Environment 3

Table 28.1 Common Services That Are Built in to


Angular

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>

You might also like