Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 212

Angular

Why scripting languages.


• There are many advantages of using a scripting language.
First, they are open source. Therefore, anyone around the
world can use it and contribute to it.
• Second, if you are a beginner, they are a great way to start
with programming languages, as they are quite easy to
learn and code.
• As we know that most scripting languages use an
interpreter, and unlike compilers, no executable file is
stored, and hence, they require less memory.
• They are portable, i.e., can run on different operating
systems.
• Scripts are also used as a prototype before building an
actual program.
What is a framework.
• Software frameworks make life easier for developers by allowing them to take control of the entire
software development process, or most of it, from a single platform.

Advantages of Framwork
• Assists in establishing better programming practices and fitting use of design patterns
• Code is more secure
• Duplicate and redundant code can be avoided
• Helps consistent developing code with fewer bugs
• Makes it easier to work on sophisticated technologies
• One could create their software framework or contribute to open-source frameworks. Hence,
there is a continuous improvement in the functionality
• Several code segments and functionalities are pre-built and pre-tested. This makes applications
more reliable
• Testing and debugging the code is a lot easier and can be done even by developers who do not
own the code
• The time required to develop an application is reduced significantly
What is MEAN Stack
• The MEAN stack is JavaScript-based framework for
developing web applications. MEAN is named
after MongoDB, Express, Angular, and Node, the four key
technologies that make up the layers of the stack.
• MongoDB - document database
• Express(.js) - Node.js web framework
• Angular(.js) - a client-side JavaScript framework
• Node(.js) - the premier JavaScript web server
• There are variations to the MEAN stack such as MERN
(replacing Angular.js with React.js) and MEVN (using
Vue.js). The MEAN stack is one of the most popular
technology concepts for building web applications.
What is Full sack
• Full stack development: It refers to the
development of both front end(client side)
and back end(server side) portions of web
application.
• Full stack web Developers: Full stack web
developers have the ability to design
complete web application and websites. They
work on the frontend, backend, database and
debugging of web application or websites.
What is Angular
• Angular is a development platform, built on
TypeScript. As a platform, Angular includes:
• A component-based framework for building
scalable web applications
• A collection of well-integrated libraries that cover
a wide variety of features, including routing,
forms management, client-server
communication, and more
• A suite of developer tools to help you develop,
build, test, and update your code
Why Angular
• One of the biggest advantage of Angular is that it is
supported by Google.
• Supports typescript : Angular applications are built
using TypeScript language, a superscript for JavaScript,
which ensures higher security as it supports types
(primitives, interfaces, etc.). It helps catch and
eliminate errors early when writing the code or
performing maintenance tasks.
• Uses HTML for UI : Angular uses HTML to define the UI
of the application.
• Angular can be easily tested.
• It has MVC pattern.
Why Angular
• Good Reusability
• Simplified Unit-Testing
• Improved Readability
• Ease of Maintenance
Difference between Angular 1 and
Angular 2
Angular CLI.
• Angular CLI is used to create projects,
generate application and library code, and
perform a variety of ongoing development
tasks such as testing, bundling, and
deployment.
Install node.
• From the command prompt, give the command
• From the url, download node and install it.
https://nodejs.org/en/download/
• Check the version in the command line using the command
C:\> node –v  This gives the node version.
Installing angular
• From the command prompt, give the command
npm install –g @angular/cli
Create a new project in Angular
• From the command line, give the command
ng new <project name>
Start angular server
• ng serve  At the command line will start the angular server at port 4200.
Angular installation check
• Run http://localhost:4200 in the browser. It generates the following
output.
ECMA script.
• ECMA Script : The full form of ECMA is European
Computer Manufacturer's Association. ECMAScript is
a Standard for scripting languages such as JavaScript,
JScript, etc. It is a trademark scripting language
specification. JavaScript is a language based on
ECMAScript. A standard for scripting languages like
JavaScript, JScript is ECMAScript. JavaScript is
considered as one of the most popular
implementations of ECMAScript.
History of ECMA Script.
• JavaScript was originally named Mocha and changed to Livescript but ultimately became
JavaScript.
• It's important to note that JavaScript came before ECMAscript and the history will tell you why.
• To start from the beginning, JavaScript derived its name from Java and initially Brendan Eich
(the creator of JS) was asked to develop a language that resembled Java for the web for
Netscape.
• Eich, however decided that Java was too complicated with all its rules and so set out to create a
simpler language that even a beginner could code in. This is evident in such things like the
relaxing of the need to have a semicolon.
• After the language was complete, the marketing team of Netscape requested Sun to allow
them to name it JavaScript as a marketing stunt and hence why most people who have never
used JavaScript think it's related to Java.
• About a year or two after JavaScript's release in the browser, Microsoft's IE took the language
and started making its own implementations such as JScript. At the same time, IE was
dominating the market and not long after Netscape had to shut its project.
• Before Netscape went down, they decided to start a standard that would guide the path of
JavaScript, named ECMAScript. The full form of ECMA is European Computer Manufacturer's
Association
ES5 features
• USE Strict is introduced. With this variables
cant be used without declaring them.
• New methods for array are introduced.
• JSON support.
• New Methods in date are added.
Features of ES6
• Let and Const are introduced.
• For..of
• Default parameters of the functions.
• Rest operator  Any number of parameters can be passed to a function
with …<variable name> as the function parameter.
• Spread Operator.
• Destructuring.
• Template literals.
• Arrow functions.
• Promises.
• Classes.
Features of ES7.
• Exponent Operator using ** and couple of functions added.
Transpiler & ts-node.
• Transpilers, or source-to-source compilers, are
tools that read the sourcecode written in one
programming language and produce the equivalent
code in another programming language
• Typescript Transpiler will convert from .ts file to its
corresponding .js file.. Converts from Typescript to
JavaScript.
• ts-node is a TypeScript execution engine and REPL
for Node.js.
Typescript.
• TypeScript is an open-source object-oriented
programming language. It was launched and
introduced on October 1st, 2012. TypeScript
follows JavaScript syntactically but adds more
features to it. It is a superset of JavaScript. It is
developed and maintained by Microsoft under
the license of Apache 2. It does not directly
run on the browser and requires a compiler to
compile and generate a TypeScript file.
Features of Typescript.
• Object-Oriented language: TypeScript provides a complete feature of an
object-oriented programming language such as classes, interfaces,
inheritance, modules, etc. In TypeScript, we can write code for both client-
side as well as server-side development.
• TypeScript is portable: TypeScript is portable because it can be executed on
any browsers, devices, or any operating systems. It can be run in any
environment where JavaScript runs on. It is not specific to any virtual-
machine for execution.
• TypeScript is just a JS: TypeScript code is not executed on any browsers
directly. The program written in TypeScript always starts with JavaScript and
ends with JavaScript. Hence, we only need to know JavaScript to use it in
TypeScript. The code written in TypeScript is compiled and converted into its
JavaScript equivalent for the execution. This process is known as Trans-
piled. With the help of JavaScript code, browsers can read the TypeScript
code and display the output.
Typescript compilation procedure
Install typescript.
• Npm install –g typescript  this will install
the typescript.
• Tsc –v  Will give the typescript version.
Enable decorators
• To enable decorators, give the following
command in the command line
• Tsc –target ES5 --experimentalDecorators
Basic building blocks of Angular
• Modules --
• Components
• Templates  A template is a form of HTML that tells Angular how to render the

component.

• Metadata
• Data binding
• Directives
• Services
• Dependency injection
Building blocks of Angular.
Angular – Modules.
• Angular apps are modular and to maintain modularity, we have Angular
modules or you can say NgModules. Every Angular app contains at least
one Angular module, i.e. the root module. Generally, it is named
as AppModule. The root module can be the only module in a small
application. While most of the apps have multiple modules. You can say, a
module is a cohesive block of code with a related set of capabilities that
have a specific application domain or a workflow. Any angular module is a
class with @NgModule decorator.
• Like JavaScript modules, NgModules can import functionality from other
NgModules, and allow their own functionality to be exported and used by
other NgModules. For example, to use the router service in your app, you
import the Router NgModule.
App.module.ts
• import { NgModule } from '@angular/core';
• import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
• import { AppComponent } from './app.component';

@NgModule({
• declarations: [
• AppComponent
• ],
• imports: [
• BrowserModule,
• AppRoutingModule
• ],
• providers: [],
• bootstrap: [AppComponent]
• })
• export class AppModule { }
Angular Component.
• A component controls one or more sections on the screen called a view. For example, if you are building a
course list application, you can have components like App Component (the bootstrapped component),
Course Component, Course Detail Component, etc.
• Inside the component, you define a component’s application logic i.e. how does it support the view—inside
a class. The class interacts with the view through an API of properties and methods.
• Every app has a main component that is bootstrapped inside the main module, i.e AppComponent. The
following code is in app.component.ts
• import { Component } from '@angular/core';

@Component({
• selector: 'app-root',
• templateUrl: './app.component.html',
• styleUrls: ['./app.component.css']
• })
• export class AppComponent {
• title = 'my-app';
• }

ngModule :
•An NgModule is a class marked by the @NgModule decorator. @NgModule takes a metadata
object that describes how to compile a component's template and how to create an injector at
runtime. It identifies the module's own components, directives, and pipes, making some of them
public, through the exports property, so that external components can use them.
BrowserModule:
•BrowserModule provides services that are essential to launch and run a browser application.
AppRoutingModule : It is an NgModule where you can configure your routes.

import { AppComponent } from './app.component';  Importing AppComponent class from


app.component.ts file..
Declarations in @ngModule: The module's declarations array tells Angular which components
belong to that module. As you create more components, add them to declarations.
Imports section : These modules are imported into the current module of ngModule.
Providers section : This section will list all the services of the project.
bootstrap: [AppComponent] means A bootstrapped component is an entry component that
Angular loads into the DOM during the bootstrap process (application launch)
• Purpose of Angular/Core
• Defines the class infrastructure for components, view hierarchies, change detection,
rendering, and event handling.
• Defines the decorators that supply metadata and context for Angular constructs. -
@Component is the decorator which is part of metadata.
• Defines infrastructure for dependency injection (DI), internationalization (i18n), and various
testing and debugging facilities.

• What is a selector:
• A selector is one of the properties of the object that we use along with the component
configuration.
• A selector is used to identify each component uniquely into the component tree,
What is metadata.
• Metadata is the data about data or information about the class. Decorators are used to do
this work.
• The whole purpose of Angular decorators is to store metadata about a class, method, or
property. When you configure a component, you are providing a metadata for that class that
tells Angular that you have a component, and that component has a specific configuration.
Each decorator has a base configuration with some default values. When the decorator is
created using the relevant factory, the default configuration is passed.
There are four types of decorators in Angular:
• Class Decorators - @ngModule decorator is used in app.module.ts to provide information
about the class AppModule.
• Property Decorators : @Input is used to communicate property data from parent to child
component.
• Method Decorators : @HostListener. This tells Angular that when an event on your host
happens, you want the decorated method to be called with the event
• Parameter Decorators : Parameter decorators are used to decorate parameters in your class
constructors. For example- @Inject. It tells Angular that what you want that parameter to be
initiated with. More about this can discussed during services in Angular.
Directives and Services.
• Directives are classes that add additional behavior to elements in your Angular applications.

• Attribute directives—directives that change the appearance or behavior of an element,


component, or another directive. ngStyle, ngClass
• Structural directives—directives that change the DOM layout by adding and removing DOM
elements. ngIf, ngFor, ngSwitch etc.,

• Services : Service is a broad category encompassing any value, function, or feature that an
application needs. A service is typically a class with a narrow, well-defined purpose. It should
do something specific and do it well.
Dependency Injecton.
• Dependencies are services or objects that a
class needs to perform its function.
Dependency injection, or DI, is a design pattern
in which a class requests dependencies from
external sources rather than creating them.
• Angular's DI framework provides dependencies
to a class upon instantiation. Use Angular DI to
increase flexibility and modularity in your
applications.
Files/Directories in Angular Project.
• Node_modules : This directory will show the modules installed by npm.
• Src/app – Directory for writing the code for the application.
• Under src/app
– App.routing.module.ts  For routing purpose.
– App.component.css  For css styling of app component.
– App.component.html  HTML file for app component.
– App.component.spec.ts  For unit testing of Angular.
– App.component.ts  Typescript file for main angular component.
– App.module.ts  It will define about the module.
• Assets – Files placed under this directory, can be accessed through http client directly and
with the browser also. Create a file test.json add some json into it and it can be accessed
through browser using the URL
http://localhost:4200/assets/test.json
• Environment – We can setup the environment for test, staging, production etc.,
• Favicon.ico  For icon of the application.
• Index.html -
• Main.ts - Angular started with main.ts.
• Then we bootstrap an angular application and we pass app.module.ts as an argument. In
app.module.ts we tell angular: "There is the app component which you should know when you try
to start yourself".
• And angular now analyze this app component, reading the set up we pass there and there
is SELECTOR app-root.
• Now, angular is enable to handle app-root in the index.html and knows rules for the SELECTOR.
• SELECTOR should insert the app components and have some HTML code - a template attached to
him - html component.
• This is how Angular application starts.

• Polyfill.ts - Angular is built on the latest standards of the web platform. Targeting such a wide
range of browsers is challenging because they do not support all features of modern browsers.
You compensate by loading polyfill scripts ("polyfills") for the browsers that you must support.
See instructions on how to include polyfills into your project below.
• Styles.css
• Test.ts – For testing purpose.
• Browserslistrc – Lists the supported browsers. From the command prompt, give the command
c:\>npx browserslist  This will give the supported browsers.
• Editorconfig – Editor configuration information is provided in this file.
• Gitignore  .gitignore is an plain text file that contains list of files/folders paths, that means,
these files are not committed to repositories while committing a projects.
• Angular.json  A file named angular.json at the root level of an Angular workspace provides
workspace-wide and project-specific configuration defaults for build and development tools
provided by the Angular CLI.
• Karma.conf.js  For testing purpose.
• Package-lock.json  package-lock. json is automatically generated for any operations where
npm modifies either the node_modules tree, or package. json.
• Package.json  Once you create new Angular application, you will see package.json file
among the newly created files and folders. package.json file locates in project root and
contains information about your web application. The main purpose of the file comes from
its name package, so it'll contain the information about npm packages installed for the
project.
• Read.md  What commands can be given at the Angular CLI.
• Next 3 files for typescript compilation options.
• Tsconfig.app.json --> The Angular CLI generates a tsconfig.app.json file which is used to build
an application.
• Tsconfig.json  TypeScript compiler configuration.
• Tsconfig.spec.json  For testing purpose.
Bootstrap Component.
• A bootstrapped component is an entry
component that Angular loads into the DOM
during the bootstrap process (application
launch). Other entry components are loaded
dynamically by other means, such as with the
router. Angular loads a root AppComponent
dynamically because it's listed by type in
@NgModule. bootstrap .
To be done in Agular.
• Assignments:
• Place a header in app.component.html and see the output.
• Add css style in styles.css for a header and check the output.
• After adding a child component, modify the individual CSS files for the
styles of paragraph both in parent and child and see the difference.
Creating a child component.
• At the command prompt, give the command
ng generate component child or
ng g c child

Open the created files and check in the visual studio of the created files.
Ng-content
• Content projection is a pattern in which you
insert, or project, the content you want to use
inside another component.
• In App.component.ts
• In App.component.html

• In child.component.ts
• Output is:

• 1. First try with a simple string of ng-content.


• 2. Next, based on a tag.
• 3. Next, Display a variable content of app.component.ts, may be a string.
4. Next, create an object with 2 fieds and display.
5. Extend it to more fields and display the same.

Assignment : Insert an employee record with the fields, id, name, dept and
designation.
Data binding and interpolation
• Interpolation
• Interpolation is a technique that allows the user to bind a value to a UI element.
• Interpolation binds the data one-way. This means that when value of the field
bound using interpolation changes, it is updated in the page as well. It cannot
change the value of the field.

• Define a variable in app.component.ts and display the content of this variable


in the app.component.html file as {{variable}}
To be demostrated:
• First, show the number.
• Then, a string value.
• Then an object. studentObj = {“id”:102, “name”:”Charan”};

Property Binding.
• Property binding in Angular helps you set values for properties of HTML elements or
directives. Use property binding to do things such as toggle button functionality, set paths
programmatically, and share values between components.

• Define a variable in app.component.ts which defines the path of the image as:

• Substitue the value of img src with imgURL in the app.component.html as in:

• Here the Attributes of HTML will be placed in square brackets and variable of ts file is in
double quotes.
Property binding – Toggling
buttons.
• Define a property in app.component.ts to disable a button and also
functions to enable and disable buttons based on property.

• Display 3 buttons. (a) Button itself (b) To enable a button (c) To Disable a
button. On click of enable and disable button, call function
correspondingly.
Template Reference
• Template variables help you use data from one part of a template in another part of the
template. Use template variables to perform tasks such as respond to user input or finely
tune your application's forms.

• Define a templat variable in app.component.html and use it in a button. On click of a button,


perform the required operation.

• In app.component.ts, write a function and perform the required operation.


Event binding
• Event binding lets you listen for and respond
to user actions such as keystrokes, mouse
movements, clicks, and touches.
Two way data binding.
• In two-way databinding, automatic synchronization of data
happens between the Model and the View.

• The ngmodel directive binds the value of HTML controls


(input, select, textarea) to application data.
• Add FormsModule in app.module.ts in both import section and imports
section.
• Create a new variable in app.component.ts.

• Bind this variable with input control in app.component.html using


ngModel.
Custom Property Binding.
• Using custom property binding to set the model property of a custom component is a great
way for parent and child components to communicate.
• @Input is used for communicating the data between Parent to Child.
• Provide a Edit box in app.component.html and make it as two way data binding with
app.component.ts file.
• In the app.component.html, Send this variable to the child component as given below:

• Import Input from @Angular/core as


• import { Component, OnInit, Input } from '@angular/core';
• Define the variable strName1 in child.component.ts as

• Display strName1 in child.component.html as


Day-2
What is webpack
• The dynamic web applications usually have lots of javascript files. These
files are either created by you or it could be third party libraries like
jquery/bootstrap etc. We include these in our index.html file
using <script> tag. When a user sends requests to our application, the
browser requests and loads these files one at a time. If you have lots of
these files, then it will make your application slow. The solution to this
problem is to merge all these files into a one or two files so that the
browser can download the entire file in one request. This is
where Webpack is used.
• Webpack is a powerful module bundler, which scans your web application
looking for javascript files and merges them into one ( or more) big file.
Webpack has the ability to bundle any kind of file like JavaScript, CSS,
SASS, LESS, images, HTML, & fonts etc.
Concepts of Webpack4
• Entry: The entry point is simply a module or a JavatScript file (defaults to ./src/index.js)
which webpack uses to start bundling. Webpack looks for the import statements in this
module and builds the dependency graph of all the dependencies. If you don't use the
default entry point i.e ./src/index.js, you need to specify it in the configuration file.
• Output: Using the output point, you tell webpack the name and path of the file(s)
where to produce the final bundle or set of bundles. By default it's ./dist/main.js for
the main bundle and you can specify your custom values in the configuration file.
• Loaders: Webpack makes use of loaders to know how to transform and bundle the
other types of assets and files, such as CSS, images or TypeScript code, other than
JavaScript and JSON which are supported by default.
• Plugins: Webpack can be extended with plugins which are used for adding features
that cant' be imlemented using loaders.
• Mode: Webpack enables deveopers to specify different configuration options for
development and production by using changing the mode parameter which can take
either the development, production or none values. By default the mode is set
to production.
Example of webpack
• Create a directory named webpack-example and switch to that directory
and give the command npm init –y  this will create base version of
package.json
• Install webpack and webpack-cli using the following command

• Create src directory and write console.log in it.


• Add start option in package.json under
scripts.
• Use npm start to build the project and files will be placed in dist folder.
• Create index.html and use main.js as the js file to execute.

• Open index.html in the browser.


Add entry, output and plugins.
• Add webpack.config.js and add the following code. entry will read from
index.js, output will produce the files in dist directory and
HtmlWebpackPlugin will create the required html file for execution.
• Install html-webpack-plugin

• Execute webpack –mode development and it gives the following output.

• Execute index.html from dist directory and see the output in console.
Merge many files into a single file.
• Install webpack-merge-include-globally

• Install babel, required to merge all the files into one.


• Modify webpack.configure.js as

• Run webpack –mode development


• Open the dist directory, you can see given js files are merged as vendor.js and gives css files
merged as vendor.css

• Open the contents of vendor.js and vendor.css, they are all merged files of given files in
webpack.configures.js.
Directives
• Directives are classes that add additional behavior
to elements in your Angular applications.
• Type of directives:
• Attribute directives—directives that change the
appearance or behavior of an element,
component, or another directive.
• Structural directives—directives that change the
DOM layout by adding and removing DOM
elements.
• Attribute Directives
• NgClass—adds and removes a set of CSS classes.
• NgStyle—adds and removes a set of HTML styles.
• NgModel—adds two-way data binding to an HTML form element.

• Structural Directive: Structural directives are responsible for HTML layout.


They shape or reshape the DOM's structure, typically by adding,
removing, and manipulating the host elements to which they are
attached. Structural directives are:
• NgIf—conditionally creates or disposes of subviews from the template.
• NgFor—repeat a node for each item in a list.
• NgSwitch—a set of directives that switch among alternative views.
Install bootstrap in Angular.
• Give the following commands to install bootstrap for angular.
npm install bootstrap
npm install jquery

After the installation, modify the angular.json with the following.

And then give ngserve and start angular server.


Test whether boostrap is installed
or not.
Add the following app.component.html
•<button [ngClass]="btn btn-primary'" type="submit"
(click)='OnSubmit()'>Submit</button>
.and in app.component.ts
•OnSubmit() {alert (“Submit button is clicked”);}
ngClass
• Single class can be set like this.
• <button [ngClass]=“’btn btn-primary'" type="submit"
(click)='OnSubmit()'>Submit</button>

• This will set the button to btn-primary in angular. Output wll be like this 
ngClass with multiple Strings.
• Setting the multiple clasess.
• Define a class in styles.css as:
• .md-button {
• padding: 0 6px 0 6px;
• margin: 16px 18px 16px 28px;
• font-size: 24px;
• text-align: center;
• text-transform: uppercase;
• }
• In app.component.html, define the multiple classes as an array of strings as
given below:
• <button [ngClass]="['btn btn-primary', 'md-button']" type="submit"
(click)='OnSubmit()'>Submit</button>
• Output will be like this :
Adding a condtion in ngClass.
• In styles.css

• In app.component.html 
• In app.component.s 

• Output will be
ngStyle
• Changes the style of the HTML elements.

• In app.component.ts, declare a variable strColor as


• In app.component.html, modify the style of the component dynamically
as

• With this, as and when the user enters the color name, color of the text is
modified.
Multiple attributes in ngStyle.
• Define 2 variables to change the color and font-size of the text in
app.component.ts

• In app.component.html, take the input from two edit boxes and apply
them to ngStyle dynamically.

• Output will be like this:


Conditioning in ngStyle.
• Add an attribute in app.component.ts
• In styles.css add the following:

• In app.component.html

• If the user types Yes in the edit box then background color of the text is
changed to green else it is changed to Red.
ngFor Directive
• NgFor is a built-in template directive that makes it easy to iterate over
something like an array or an object or array of objects.

• Create an array of objects in app.component.ts as

• Add the following code in app.component.html,


which iterates every element of the list and displays the names. And

output will be like this


Display in a table using ngFor.
• In app.component.ts, define array of objets 

• In app.component.html, iterate the array of objects and display them in a


table.
*ngIf
• ngIf is used for conditinal rendering.
• Based on a condition, lets display the text on the browser.
• In the app.component.ts

• In app.component.html, add the following code:


ngIf for toggling
• In app.component.ts, define a variable

• In app.component.html 

• Output will be :
*ngIf for displaying Login or
register button.
• In app.component.ts

• In App.component.html 

• Output is:
ngSwitch.
• Based on strData, its corresponding case is selected and displayed.
• <input type="text" [(ngModel)]="strData">

• <div [ngSwitch]="strData">
• <div *ngSwitchCase="1">One</div>
• <div *ngSwitchCase="2">Two</div>
• <div *ngSwitchCase="3">Three</div>
• <div *ngSwitchCase="4">Four</div>
• <div *ngSwitchCase="5">Five</div>
• <div *ngSwitchDefault>This is default...</div>
• </div>
Day-3
Pipes, what is a pipe.
• Pipes are a useful feature in Angular. They are
a simple way to transform values in an
Angular template. There are
some built in pipes, but you can also build
your own pipes.
• A pipe takes in a value or values and then
returns a value. This is great for simple
transformations on data but it can also be
used in other unique ways
Built in pipes.
• Following are the built in pipes
• 1. Lowercase Pipe.
• 2. Uppercase Pipe
• 3. DatePipe
• 4. CurrencyPipe.
• 5. JsonPipe
• 6. PercentPipe.
• 7. DecimalPipe.
• 8. SlicePipe.
• 9. Async Pipe
Uppercae and Lowercase pipes.
• Define a variable strToConvert in app.component.ts and in
app.component.html

• Output will be:


Currency Pipe.
• Create a variable iCurrencyData in app.component.ts and use it in currency Pipe
as given below:

• Output will be like this:


• After USD : “US Dollar is mentioned. That string
will be displayed. When ‘code’ is given, country
code will be displayed as EUR.


Date pipe.
• Define these variables in app.component.ts.

• Display date using date pipe with various formats.


Output of date pipe
JSON pipe
• Json pipe displays content of json object.
• Define json object and array of json objects in
app.component.ts

• Display them using json pipe in app.component.html


Output of Json pipe code
Decimal Pipe
• Define a variable in the app.component.ts

• Display original value and its decimal format value in app.component.html

• Output is
Percent Pipe
• Angular PercentPipe is an angular Pipe API that formats a number as a percentage.
• Define a variable in app.component.ts as:

• Show the percent using percent pipe in app.component.html


• Format is {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}

• Output :
Slice Pipe.
• Slices the string using slice pipe.
• Define a string in app.component.ts as

• Define various types slices in app.component.html

• Output is
Assignment – 12 & 13
• 12. Create three edit boxes. First edit box when take the string from the user. Second and third edit
boxes will take starting and ending number for slice. If the first edit box takes string as "Munnar" and
second and third edit box takes 2 numbers as 1 and -1 then it should display "unna" as the output.
• 13. Modify the above program as if the second input is zero then second input should not be considered.
If the second input is 0 then the command should be
• string | slice:startData. Hint: You can use *ngIf, else and ng-template directives.
• <input type="text" [(ngModel)]="strForSlicePipe">
• <input type="number" [(ngModel)]="iStartData">
• <input type="number" [(ngModel)]="iEndData">

Original Data : {{strForSlicePipe}} <br>
• <div *ngIf='iEndData != 0; else zeroBlock'>
• Sliced data 2:5 (2nd char to 5th Char): {{strForSlicePipe |slice:iStartData:iEndData }}<br>
• </div>

<ng-template #zeroBlock>
• Sliced data 2:5 (2nd char to 5th Char): {{strForSlicePipe |slice:iStartData}}
• </ng-template>
Creating a custom pipe
• Generate a new pipe from command line as given below:

• Add the following code in temp-converter.pipe.ts, modify unknown to the data type we
require
• Add two variables in app.component.ts 

• Add the code in app.component.html as

• Output of this code is :

• Demo for Uppercase of a


given string using custom
pipe.
Pure vs Impure pipes.
• Pipe can be made pure or impre with a flag in
the pipe.ts as “pure:true/false”. If the pure
flag is true then it is pure pipe else it is impure
pipe.
• What is pure pipe or Impure Pipe.
Whenever the state of the component is
modified then pipe is executed is called
Impure Pipe. Pure pipe is executed only when
it is called.
• Let us take an example of displaying a table based on array of objets as
shown below:

• A pipe is developed to filter based on the First name as below:


• App.component.ts is adding records to the array as show below:
• App.component.html displays the content of array of objects using nfFor
with filter.
• On filtering, it shows like this:

• Lets say we add two button in the html as shown below:


• Functions of these buttons are:

• On click of AddUser button will not have an impact on pipe as it is not


called after the change in the state of the object. This is called pupre pipe.
This behavior can be modified by changing the pipe to impure pipe, that
is, adding a flag pure:false in the pipe.ts file. But Impure pipes are called
everytime there is change in the state of the component, hence there is an
performance impact.
• There is an error created in the pipe, lets see if you can resolve it.
• Reset() needs to be looked into. You need to correct them to make it
work.
Pure vs Impure
• Create two pipes named purePipe and ImpurePipe.

• Ng g pipe purepipe --skip-tests


• Ng g pipe impurepipe --skip-tests
• Content of pupre pipe :
• Content of Impure Pipe is

• Define two variables in app.component.ts

• Use the pipe in html as shown:


• Open console to see how exactly both the pipes are behaving:

• Pupre pipe is called whenever it is invoked but impure pipe is called whenever the
state of the object is modified. Here the component is modified internally.
Observables.
• Promises are same as discussed in typescript.
• Observables provide support for passing messages between parts of your application. They are used
frequently in Angular and are a technique for event handling, asynchronous programming, and
handling multiple values.
• The observer pattern is a software design pattern in which an object, called the subject, maintains a
list of its dependents, called observers, and notifies them automatically of state changes. This pattern
is similar (but not identical) to the publish/subscribe design pattern.
• Observables are declarative—that is, you define a function for publishing values, but it is not
executed until a consumer subscribes to it. The subscribed consumer then receives notifications until
the function completes, or until they unsubscribe.
• An observable can deliver multiple values of any type—literals, messages, or events, depending on
the context. The API for receiving values is the same whether the values are delivered synchronously
or asynchronously. Because setup and teardown logic are both handled by the observable, your
application code only needs to worry about subscribing to consume values, and when done,
unsubscribing. Whether the stream was keystrokes, an HTTP response, or an interval timer, the
interface for listening to values and stopping listening is the same.
• Because of these advantages, observables are used extensively within Angular, and for application
development as well.
• A program will be demonstrated during Forms module.
Day-4
Angular Service
• Introduction to services and dependency injection.
• Service is a broad category encompassing any value, function, or feature that an application needs.
A service is typically a class with a narrow, well-defined purpose. It should do something specific
and do it well.
• Angular distinguishes components from services to increase modularity and reusability. By
separating a component's view-related functionality from other kinds of processing, you can make
your component classes lean and efficient.
• Ideally, a component's job is to enable the user experience and nothing more. A component should
present properties and methods for data binding, in order to mediate between the view (rendered
by the template) and the application logic (which often includes some notion of a model).
• A component can delegate certain tasks to services, such as fetching data from the server,
validating user input, or logging directly to the console. By defining such processing tasks in
an injectable service class, you make those tasks available to any component. You can also make
your application more adaptable by injecting different providers of the same kind of service, as
appropriate in different circumstances.
• Angular doesn't enforce these principles. Angular does help you follow these principles by making
it easy to factor your application logic into services and make those services available to
components through dependency injection.
Http Service
• Http Service will help us fetch external data,
post to it, etc. We need to import the http
module to make use of the http service.
• Import it in app.module.ts
import { HttpModule } from '@angular/http';
Dependency Injection.
• Dependencies are services or objects that a class needs to perform its
function. Dependency injection, or DI, is a design pattern in which a class
requests dependencies from external sources rather than creating them.
• Angular's DI framework provides dependencies to a class upon
instantiation. Use Angular DI to increase flexibility and modularity in your
applications.
• Dependency Injection (DI) is a technique in which a class receives its
dependencies from external sources rather than creating them itself.
Which portion of the code is better
Objeserve the following code.
I. public class TextEditor {
private SpellChecker spellChecker;
public TextEditor() {
spellChecker = new SpellChecker(); }}

Observe the following code and tell which is beneficial compared to both.
II. public class TextEditor {
private SpellChecker spellChecker;
public TextEditor(SpellChecker spellChecker) {
this.spellChecker = spellChecker; }}
Benefits of Dependency Injection.
• loosely coupled
• Easier to Test
• Reusing the Component

• Angular Depedency Framework:


Consumer
• The Consumer is the class (Component, Directive, or Service) that needs
the Dependency. In the above example, the AppComponent is the
Consumer.
• Dependency
• The Service that we want to in our consumer. In the above example
the ProductService is the Dependency
Creating a service.
• From the command line, generate the service using
ng g service Product  It will create the file Product.service.ts.

• Create Product.ts as given below:


• ProductService is having one function which returns the list of products.
All the related functionalities of Product can be written in ProductService.
Then components can make use of these services as libraries without
rewriting them.
• In App.component.ts

• In app.component.html 
Output of Service.
Injector.
• The Angular Injector is responsible for instantiating the dependency and
injecting it into the component or service.
• The Injector we are using is a Module Injector. That means this injector is
injected in the root module which is ngModule.
• The ModuleInjector can be configured in one of two ways:
• Using the @Injectable() providedIn property to refer to @NgModule(),
or root.  This is in the service.ts file.
• Using the @NgModule() providers array.  This is another way of
injecting the service in the module. Previous way of injecting the service
can be removed and name of the service can be added in the providers
array at @NgModule() in app.module.ts file.
Creating a Logging Service.
• Create a Logger service with the command:

• Add the function log in LoggerService.ts:


• Add the following code in app.component.ts

• Click on the button to fetch the records from the service and check the
console log. Output in the console log is:
EventEmitter.
• Event Emitter emits the data.
• In child.component.ts 

• In child.component.html  On every keystroke, one function is called and


that emits the entered data to the parent.
• In app.component.html 

• In app.component.ts 

• Output is :


BrowserModule and
CommonModule
• BrowserModule – The browser module is
imported from @angular/platform-browser
and it is used when you want to run your
application in a browser.

• CommonModule – The common module is


imported from @angular/common and it is
used when you want to use directives - NgIf,
NgFor and so on.
Angular Module Vs Javascript
Module
• A JavaScript module is an individual file with JavaScript code, usually containing a class or a
library of functions for a specific purpose within your application. JavaScript modules let you
spread your work across multiple files.
• An NgModule is a class marked by the @NgModule decorator with a metadata object that
describes how that particular part of the application fits together with the other parts.
NgModules are specific to Angular. While classes with an @NgModule decorator are by
convention kept in their own files, they differ from JavaScript modules because they include
this metadata.
• The @NgModule metadata plays an important role in guiding the Angular compilation
process that converts the application code you write into highly performant JavaScript code.
The metadata describes how to compile a component's template and how to create
an injector at runtime. It identifies the NgModule's components, directives, and pipes, and
makes some of them public through the exports property so that external components can
use them. You can also use an NgModule to add providers for services, so that the services
are available elsewhere in your application.
Angular Module Vs Javascript
Module
• The root NgModule starts with import statements to import JavaScript
modules. It then configures the @NgModule with the following arrays:
• declarations: The components, directives, and pipes that belong to the
NgModule. A new application project's root NgModule has only one
component, called AppComponent.
• imports: Other NgModules you are using, so that you can use their declarables.
The newly generated root NgModule imports BrowserModule in order to use
browser-specific services such as DOM rendering, sanitization, and location.
• providers: Providers of services that components in other NgModules can use.
There are no providers in a newly generated root NgModule.
• bootstrap: The entry component that Angular creates and inserts into
the index.html host web page, thereby bootstrapping the application. This
entry component, AppComponent, appears in both the declarations and
the bootstrap arrays.
Exporting from a module
• An export what you put is the exports
property of the @NgModule decorator. It
enables an Angular module to expose some of
its components/directives/pipes to the other
modules in the applications. Without it, the
components/directives/pipes defined in a
module could only be used in that module.
Angular Libraries
• Many applications need to solve the same general problems, such as
presenting a unified user interface, presenting data, and allowing data
entry. Developers can create general solutions for particular domains that
can be adapted for re-use in different applications. Such a solution can be
built as Angular libraries.
• Angular Material is an example of a large, general-purpose library that
provides sophisticated, reusable, and adaptable UI components.
How to launch an application.
• Make the build with the command ng build.

• This will create the dist directory in that project name directory is created and required
files are created along with index.html.
• User needs to execute index.html. All the dependent files are created in this directory
only. To say index.html that all the dependent files are there from this directory, we
need to specify –base-href ./
Create a new module
• Create a new module and a component under that module with the
following commands:
• Student.module.ts is created and it will be like this:

• Student component is created under student module and a function is


created to return a name.
• Include StudentModule in imports section in the AppModule as shown
below:

• Import StudentComponent in app.component.ts and use the function of


StudentComponent as:

• Include this code on click of a button


Output of the code in the console..
Day-5
What are Angular forms.
• Handling user input with forms is the cornerstone of many common
applications. Applications use forms to enable users to log in, to update a
profile, to enter sensitive information, and to perform many other data-
entry tasks.
• Angular provides two different approaches to handling user input through
forms: reactive and template-driven. Both capture user input events from
the view, validate the user input, create a form model and data model to
update, and provide a way to track changes.
What is a Reactive Form.
Registering input form controls to
Angular.
• Add ReactiveFormsModuel in Imports section of app.module.ts

• Import FormGroup, FormControl and Validators in app.component.ts


• Define FormGroup and add controls in it using FormControls in
app.component.ts. On Submit, we are retreiving the values of uid and
pwd and setting the value of pwd to admin123.

• Connect html form and model (ts) file as given below. Specify the
formGroup and formControlName in the form.
• Output of the form is :
Reactive Forms validator.
• In app.component.ts, add required and minLength validator of validator
framework while creating the control in FormControl.

• Required by the validator framework in the html to obtain the value of


the uid.
• Dirty & touched
• Apart from checking valid we are also checking for the dirty & touched.
Because we do not want the application to display the error when the
form is displayed for the first time. We want to display errors only after
the user has attempted to change the value.
The dirty & touched properties help us do that.
• dirty: A control is dirty if the user has changed the value in the UI.
touched: A control is touched if the user has triggered a blur event on it.

• First, we need to disable browser validator by adding


the novalidate attribute to the <form> element as shown below. If this
attribute is present then the form is not validated by the built-in HTML5
validation when submitted.

• In app.component.html

• Output is:
Form States and CSS States
Input fields have the following states:
•untouched The field has not been touched yet
•touched The field has been touched
•pristine The field has not been modified yet
•dirty The field has been modified
•invalid The field content is not valid
•valid The field content is valid
They are all properties of the input field, and are either true or false.
•Forms have the following states:
•pristine No fields have been modified yet
•dirty One or more have been modified
•invalid The form content is not valid
•valid The form content is valid
•submitted The form is submitted
ngModelGroup.
• The NgModelGroup is used to create a top-level form group Instance,
and it binds the form to the given form value.
• In app.component.ts
• In app.component.html

• Output is :
RESTful services
• RESTful web services are built to work best on
the Web. Representational State Transfer
(REST) is an architectural style that specifies
constraints, such as the uniform interface,
that if applied to a web service induce
desirable properties, such as performance,
scalability, and modifiability, that enable
services to work best on the Web.
Install json server
• With npm install –g json-server in the command line will install the json
server.


Create db.json
• Creat db.json in the location of package.json.
Start the json server
Asynchronous Response Handling
• The Asynchronous Response Handler pattern addresses the problem of
blocking on the client thread that calls a service. It enables clients to do
other things once the request has been sent.
RxJS
• RxJS stands for *R*eactive E*x*tensions
for *J*ava*S*cript, and it’s a library that gives
us an implementation of Observables
for JavaScript.
Angular Http Service.
• The HttpClient is used to perform HTTP requests and it imported form
@angular/common/http.
• The HttpClient is more modern and easy to use the alternative of HTTP
Service.

• HttpClient is an improved replacement for Http Service. They expect to


deprecate Http in Angular 5 and remove it in a later version.

• To use http get/put/post delete methods from Angular, we need to


create the object of HttpClient in Depedence Injection mode.
Observable<Response> object
• Observables provide support for passing messages between parts of your
application. They are used frequently in Angular and are a technique for event
handling, asynchronous programming, and handling multiple values.
• The observer pattern is a software design pattern in which an object, called
the subject, maintains a list of its dependents, called observers, and notifies
them automatically of state changes.
• Observable is a function that converts the ordinary stream of data into
an observable stream of data. You can think of Observable as a wrapper around
the ordinary stream of data.
• Observable stream or simple Observable emits the value from the
stream asynchronously. It emits the complete signals when the stream
completes or an error signal if the stream errors out.
• Observables are declarative. You define an observable function just like any
other variable. The observable starts to emit values only when someone
subscribes to it.
Create User class
• Add HttpClientModule in app.module.ts
RestService
• Generate a new service for RestService  ng g service Rest
RestService.
• App.component.ts
• In App.component.html
Day - 6
What is a router
• Angular Router is a powerful JavaScript router built and
maintained by the Angular core team that can be installed
from the @angular/router package. It provides a complete
routing library with the possibility to have multiple router
outlets, different path matching strategies, easy access to
route parameters and route guards to protect components
from unauthorized access.
• The Angular router is a core part of the Angular platform. It
enables developers to build Single Page Applications with
multiple views and allow navigation between these views.
• Router
• The Angular Router is an object that enables navigation from one
component to the next component as users perform application tasks like
clicking on menus links, buttons or clicking on back/forward button on the
browser. We can access the router object and use its methods
like navigate() or navigateByUrl(), to navigate to a route
• Route
• Route tells the Angular Router which view to display when a user clicks a
link or pastes a URL into the browser address bar. Every Route consists of
a path and a component it is mapped to. The Router object parses and
builds the final URL using the Route
• Routes
• Routes is an array of Route objects our application supports
• RouterOutlet
• The outerOutlet is a directive (<router-outlet>) that serves as a
placeholder, where the Router should display the view
• RouterLink
• The RouterLink is a directive that binds the HTML element to a Route.
Clicking on the HTML element, which is bound to a RouterLink, will result
in navigation to the Route. The RouterLink may contain parameters to be
passed to the route’s component.
• RouterLinkActive
• RouterLinkActive is a directive for adding or removing classes from an
HTML element that is bound to a RouterLink. Using this directive, we can
toggle CSS classes for active RouterLinks based on the current RouterState
• ActivatedRoute
• The ActivatedRoute is an object that represents the currently
activated route associated with the loaded Component.
Navigation
• Navigation is one of the important aspect in a web
application. Even though a single page application (SPA) does
not have multiple page concept, it does moves from one view
to another view Providing clear and understandable
navigation elements decides the success of an application.
• Angular provides extensive set of navigation feature to
accommodate simple scenario to complex scenario. The
process of defining navigation element and the corresponding
view is called Routing. Angular provides a separate
module, RouterModule to set up the navigation in the
Angular application.
URL Entry
• A router will have the links and when a link is clicked on, it will choose a
path and that path is pointed by a component. That means when a link is
clicked on control is routed to a specific component.
Creating the router
• Generate the required components as in (a) About (b)Contact Us (c)
Products (d) NoPageFound.  use ng g c for all these components.
• Add in app-routing-module.ts
Add entries in app-
routing.module.ts
• Add path entries to app-routing.modules.ts and right now, ignore
canActivate. This is for canActivate Guard. Exports is exporting this
router for the whole application.
• Code to app the router links in app.component.html
• Code in app.component.ts
• Code in ProductService.ts
• Code in product.component.ts
• Code in product.component.ts
• Code in product.component.ts
• Code in product.component.html
• Create No Page Found component and have the following code in
nopagefound.component.html. It will be called when the given URL in the
browser is not part of given routes in app-routes.component.ts
• For Query params, create a component users-display and add the
following code. In query params, we can send any number of params and
if there are 5 params defined, we can send 2 or 3 or 4 or 5. For the sent
params, data will go for the rest undefined will be there.
• Create a service named AuthenticationService (ng g service
AuthicationService). This will check whether the user has given the right
user id and password or not.
• Create AuthGuardService by ng g service AuthGuard.
• Add the following code in authguard.service.ts
Output
Child routes.
• Routes defined in the parent route is called a child route.
• Here it is siblings.

• Here it is the child routes.


Day - 7
Testing angular applications.
• Poorly written code, buggy functionality, and bad refactoring practices can lead to unreliable
applications. Writing good tests will help detect these types of problems and prevent them
from negatively affecting your application. It’s vital that you thoroughly test your application
if you want to make it sustainable and supportable for years to come. A core purpose of
writing tests is to help guard against breaking application functionality when you have to add
new features or make bug fixes later on.
• If you’ve developed an Angular application, you may know that Angular is a great framework
for building testable web and mobile web applications. One of the goals in writing Angular
was to make it a testable framework, and it shows.
• Although testing Angular applications is of utmost importance, figuring out how to do that
has been challenging until now.
• Angular testing an be done for:
• 1. Components.
• 2. Pipes
• 3. Services.
• 4. Directives
• 5. Routing.
What is Jasmine
• Jasmine is a JavaScript testing framework that supports
a software development practice called Behaviour-
Driven Development, or BDD for short. It’s a specific
flavour of Test-Driven Development (TDD).
• Jasmine, and BDD in general, attempts to describe tests
in a human readable format so that non-technical
people can understand what is being tested. However
even if you are technical reading tests in BDD format
makes it a lot easier to understand what’s going on.
• For example if we wanted to test this function:

• We would write a Jasmine test spec like so:

• The describe(string, function) function defines what we call a Test Suite, a collection
of individual Test Specs.
The it(string, function) function defines an individual Test Spec, this contains one
or more Test Expectations
• The expect(actual) expression is what we call an Expectation. In conjunction with
a Matcher it describes an expected piece of behaviour in the application.
• The matcher(expected) expression is what we call a Matcher. It does a boolean
comparison with the expected value passed in vs. the actual value passed
to the expect function, if they are false the spec fails.
Behavior Driven Development.
• BDD (Behavior-driven development) is a
process that easies the conversion of user
features specifications to code that developers
must write to satisfy them. In fact, with BDD
tools developers can write test cases in a
human-readable and non-technical language.
• There are many libraries that allow developers
to write tests in BDD-style; the most used ones
are Cucumber, JBehave and Behat.
• Every step must start with one of the
keywords Given, When, Then, But or And. Cucumber treats them all the
same, but for developers these keywords must have different purposes:
• Given: to put the system in a known state
• When: to describe the key action the user performs
• Then: to observe outcomes
• And or But: to use if there are several givens, whens or thens

• One of the example to test login page using BDD:


Jasmine Provided Matchers.
• Equality: toEqual
• They will pass
– expect(true).toEqual(true);
– expect([1, 2, 3]).toEqual([1, 2, 3]);
• They will faile:
– expect(5).toEqual(12);
– expect([1, 2, 3, 4]).toEqual([1, 2, 3]);
– expect(true).toEqual(100);
• Identity: toBe
• At first, the toBe matcher looks a lot like the toEqual matcher, but it’s not
exactly the same. toBe checks if two things are the same object, not just if
they are equivalent.
– var spot = { species: "Border Collie" };
– var cosmo = { species: "Border Collie" };
– expect(spot).toEqual(cosmo); // success;
– equivalent expect(spot).toBe(cosmo); // failure; not the same object

– expect(spot).toBe(spot); // success; the same object


• Same for arrays as well
– var arr = [1, 2, 3]; expect(arr).
– toEqual([1, 2, 3]); // success;
– equivalent expect(arr).toBe([1, 2, 3]); // failure; not the same array
• Yes or No? toBeTruthy, toBeFalsy
• If you want to make sure something is literally true or false and nothing
else, use the toEqual matcher like so:
– expect(myVariable).toEqual(true);
– expect(myOtherVariable).toEqual(false);
• The same can be written inusing toBeTruthy() or toBeFalsy()
– expect(myVariable).toEqual(true);
– expect(myOtherVariable).toEqual(false);
• Check If an Element Is Present with
toContain
• Sometimes you want to verify that an element is a member of an
array, somewhere. To do that, you can use the toContain matcher:
– expect([1, 2, 3, 4]).toContain(3);
– expect(["Penguin", "Turtle", "Pig", "Duck"]).toContain("Duck");

• Is It NaN? toBeNaN
• Like toBeNull, toBeNaN checks if something is NaN:
– expect(5).not.toBeNaN(); // success
– expect(0 / 0).toBeNaN(); // success
• Check If an Element Is Present with
toContain
• Sometimes you want to verify that an element is a member of an
array, somewhere. To do that, you can use the toContain matcher:
– expect([1, 2, 3, 4]).toContain(3);
– expect(["Penguin", "Turtle", "Pig", "Duck"]).toContain("Duck");

• Is It NaN? toBeNaN
• Like toBeNull, toBeNaN checks if something is NaN:
– expect(5).not.toBeNaN(); // success
– expect(0 / 0).toBeNaN(); // success
• Comparators: toBeGreaterThan,
toBeLessThan
• The toBeGreaterThan and toBeLessThan matchers check if something is
greater than or less than something else. All of these will pass:

– expect(8).toBeGreaterThan(5);
– expect(5).toBeLessThan(12);
– expect("a").toBeLessThan("z"); // Notice that it works for strings too!

Setup and Teardown.
• Sometimes in order to test a feature we need to perform some setup,
perhaps it’s creating some test objects. Also we may need to perform
some cleanup activities after we have finished testing, perhaps we need
to delete some files from the hard drive.
• These activities are called setup and teardown (for cleaning up)
and Jasmine has a few functions we can use to make this easier:
• beforeAll() - This function is called once, before all the specs in a test suite
(describe function) are run.
• afterAll() - This function is called once after all the specs in a test suite are
finished.
• beforeEach() - This function is called before each test specification
(it function) is run.
• afterEach() - This function is called after each test specification is run.
What is Karma
• Manually running Jasmine tests by refreshing a browser tab repeatedly
in different browsers every time we edit some code can become tiresome.
• Karma is a tool which lets us spawn browsers and run Jasmine tests inside
of them all from the command line. The results of the tests are also
displayed on the command line.
• Karma can also watch your development files for changes and re-
run the tests automatically.
• Karma lets us run Jasmine tests as part of a development tool chain which
requires tests to be runnable and results inspectable via the command
line.
• It’s not necessary to know the internals of how Karma works. When using
the Angular CLI it handles the configuration for us
Installing Karma and configuration.
Testing components.
• Create a new project. (ng new test-project).
• Run ng test  It will open the result in the browser.
• Enter the following code in app.component.ts

Testing A Component. In
app.component.spec.ts
beforeEach(), afterEach(),
beforeAll(), afterAll().
Testing a service.
• Creat a service Authentication (ng g service Authentication).
• Add the following code in the service.

• In authentication.service.spec.ts 
What is front end performance.
• My simplest definition is “the time it takes for an application to become usable.” For me,
this is challenging to wrap my head around because “usable” can be interpreted in different
ways by different people (or maybe the same person on different days).
• You could argue, when looking at something like server response time there’s one definition
for “is it usable?” The overall response time. Before the server responds, it’s 0% usable. The
user hasn’t received the response and they can’t do anything without that. Once the server
has responded it’s now 100% usable for the user (or at least for the client to make it usable).
With that, improving the server response time will improve the time it takes the server to
“become usable.”
• When looking at frontend performance it becomes less straightforward. Rarely, it’s exactly
0% or 100% usable, but rather somewhere between during an application’s life cycle. There
are a large number of variables that can affect the usability: the actual feature code
efficiency (eg: maybe using concat vs push in a large loop), network latency, server response
time, server response size, JavaScript and CSS file size, browser, available resources on the
client, caching, long running tasks, loading states, etc
Peformance KPIs.
• First Paint (FP): the time it takes to render the first pixels on the screen,
something visually different from the previous page
• First Contentful Paint (FCP): the time it takes to render the first element or
piece of content
• First Meaningful Paint (FMP): the time it takes the most important content
to load, often referred to as the hero content
• Time to First Byte (TTFB): the time it takes from the start of the request to
receiving the first byte.
• Time to Interactive (TTI): the time is takes for the application to render and
be ready to handle user input
• Long Running Task: a long running task is any task that takes longer than 50
milliseconds to complete
• First Input Delay: the time it takes from the user interacting (eg: clicking a
button) to when the browser responds
Light house.
• Lighthouse is a tool available in Chrome
Devtools.


Best Practices and Improve
Frontend Performance
• 1. Minify Resources
• Minification of resources refers to the process of removing unnecessary,
redundant data from your HTML, CSS, and JavaScript that are not required
to load.
• Check out the following tools to generate an optimized version of your
HTML, CSS, and JavaScript codes.
• HTML: PageSpeed Insights, HTML Minifier.
• CSS: cssmin.js, Coverage tool in Chrome Dev Tools, YUI Compressor.
• JavaScript: JSMin, Coverage tool in Chrome Dev Tools.
2. Reduce the Number of Server Calls
•In general more calls your frontend makes to the server, the more time it
gets to load. This is because sending any request to the server requires full
communication before the page can be rendered. You can follow multiple
ways to reduce the number of server requests necessary for the page to load.
•Use CSS Sprites — This is one of the easiest ways to reduce the number of
server calls. Instead of loading ten individual images to the site, sprite loads
one single image file combined using a collection of images. You can
use background-image and background-position properties in CSS to display
the desired image segment. By doing this, you’re reducing the number of
server requests required.
•Reduce third-party plugins that make a large number of external requests.
•Prevent broken links to files that don’t exist.

3. Remove Unnecessary Custom Fonts


•Custom fonts have become very popular as it helps to add personalization to
the website. However, they also come at a performance cost.
4. Compress Files
• Compress the files before they are loaded so that time consumption to load
the file is less.

5. Optimize the Images


Optimizing the image size will take less time to load, hence the performance
of the project will increase.

6. Apply Lazy Loading


•Lazy loading helps to improve frontend loading times further. With lazy
loading, the web page loads only the required content first and loads the
remaining content when the user needs it.
7. Caching
•Each time there is a unique visit, everything from the HTML to CSS to
JavaScript needs to be downloaded individually. This leads to slower data
loading times.
•The best way to prevent this issue is to use the caching options. If
appropriately configured, browsers will store the files in their local cache and
avoid loading the same assets for subsequent page visits from the server.
•Apart from the browser cache, few other caching options are available to
improve the loading time.
•Cache server — User request is sent to the nearest cache server from a
collection of cache servers. (e.g.: Content Delivery Networks.)
•Memory cache — By storing certain parts of data in memory (e.g.: JavaScript
variables) without reloading them for route changes.
•Disc cache — Similar to memory cache, except it makes use of conventional
file storage typically handled by the browser.
8. Enable Prefetching
•Resource prefetching is another performance-enhancing technique you can
use to optimize the frontend data loading.
•As developers, you know your application better than the browser does. So
Prefetching uses this information to hint the browser about the resources it
might require in the future.
•Prefetching loads the resource in anticipation of their need to reduce the
waiting time of the resource. There are mainly three types of prefetching. While
link prefetching being the most popular and widely used method, DNS
prefetching and prerendering are also helpful options.
•Link Prefetching
•Link prefetching enables a browser to gather the resources that a user is likely
to request in the nearest future. Thus, developers can assume where users are
likely to visit a specific webpage.
•However, link prefetching only works with cacheable resources like images and
JavaScript.
•DNS Prefetching
•Whenever a user requests an asset hosted in a specific IP address, a DNS
lookup is performed to find the domain name that the IP address belongs to.
• DNS prefetching allows the browser to performs the DNS lookup for links
in the webpage in the background while the user browsers the current
page to minimize the latency when a user clicks on a link with DNS
prefetch enabled.
9. Use a Content Delivery Network
• When the user is far from the server geographically, latency increases.
Moreover, request load could also impact the content serving time.
• The loading speed of frontend content, including HTML pages,
stylesheets, JavaScript files, and images, can be optimized using a CDN. A
content delivery network (CDN) is a group of servers distributed across
several geographical locations that store a cached version of the content
to deliver fast to the end-user.
Memory leakage
• In Javascript, without declaring var/let in the
function makes the variable global. This will
have the variable till the end.
• Timers and Observables, ensure you release
the memory in ngOnDestroy().

You might also like