Angular Notes

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 15

Angular

Introduction
 Angular is a TypeScript based full-stack web framework for building
web and mobile applications.
 One of the major advantages is that the Angular support for web
application that can fit in any screen resolution.
 Angular application is fully compatible for mobiles, tablets, laptops
or desktops.
 Angular has an excellent user interface library for web developers
which contains reusable UI components.
Pre-requisites
the basic knowledge on
o HTML,
o CSS and
o OOPS concepts.
o TypeScript and
o JavaScript.

Applications(Some of the popular website using Angular Framework)


 Weather.com − It is one of the leading forecasting weather report
website.
 Youtube − It is a video and sharing website hosted by Google.
 Netflix − It is a technology and media services provider.
 PayPal − It is an online payment system.
Single page application
 A Single page application is a web application /website that
interacts with user by dynamically rewriting current web page with
new data from webserver.
 This means the main UI gets loaded once and the other features are
loaded on demand / depending on user actions.
 In production, this means that there is just 1 index.html file with
CSS bundle and JavaScript bundle.
 This is advantageous especially when there is rich client-side
functionality. SPA can load more quickly since full page reloads are
rare.
e.g. page with header, footer in SPA only the stuff in between is
loaded instead of the entire page. This gives performance
improvements.
 Bazel − we will be able to build and develop our
backends/frontends with the same tool. It will provide faster
building time. Incremental build. This explains that the codebase
will only trigger the smallest rebuild possible. Further, it will help to
build and deploy only what has changed rather than the entire
Application.
 Ivy - Rendering engine. Translate the templates & components into
regular HTML and Javascript that browser can understand.
Generate considerable smaller bundles make incremental
compilation easier.
 Lazy loading − is a technique in Angular that allows you
to load JavaScript components asynchronously when a specific
route is activated. It improves the speed of the
application load time by splitting the application into several
bundles. When the user navigates through the app, the bundles
are loaded as required.
 Differential loading − When you create an application, Angular
CLI generates modules and this will be loaded automatically then
browser will render the data.

Installation

Node.js must be installed in your system..

Command to install node.js


https://nodejs.org/en/
to check node version use following command

node --version
then check npm version using following command

npm –v

now, to install angular run following command-on-command


prompt.

npm install -g @angular/cli


or
to install specific version use
npm install -g @angular/cli@15.2.8
now to check angular is install run following command,
ng version

here, ng is the CLI application used to create, manage and run Angular
Application. It written in JavaScript and runs in NodeJS environment.

Note: Current version of Angular-cli is 16.0.2

To create new project in angular following command is used

ng new <project name>

 To run your application following command is used

ng serve --open

or

ng serve -o

Component in Angular
 Components are the most basic UI building block of an Angular app.
An Angular app contains a tree of Angular components.
 Angular components are a subset of directives, always associated
with a template. Unlike other directives, only one component can be
instantiated for a given element in a template.
 A component must belong to an NgModule in order for it to be
available to another component or application. To make it a
member of an NgModule, list it in the declarations field of
the NgModule metadata
 A Component in Angular comprises of functionality
 It contains three parts
o Template(View or HTML)
o Class (Code or Typescript data and methods)
o Metadata (information)

 To generate component following command is used


ng generate component <component name>
or
ng g c <component name>

 selector: A CSS selector that tells Angular to create and insert an


instance of this component wherever it finds the corresponding tag
in template HTML.
 templateUrl: The module-relative address of this component's
HTML template.
 providers:An array of dependency injection providers for services
that the component requires.
 StyleUrls:its an array of style paths applied to this template

Component Hierarchy

Data Binding
 Angular supports two-way data binding.
 Add binding markup to the template HTML to tell Angular how to
connect both sides.
 diagram shows the four forms of data binding markup
Interpolation
Angular interpolation is used display a component property in the respective
view template with double curly braces syntax. We can display all kind of
properties data into view e.g. string, number, date, arrays, list.

Advantages of interpolation
 Display simple properties – Interpolation can be used to display
and evaluate strings into the text between HTML element tags and
within attribute assignments.
 Evaluate arithmetic expressions – Another usage of interpolation is
to evaluate arithmetic expressions present within the curly braces.
 Invoke methods and display return values – We can also
invoke/call methods on hosting component views within
interpolation expressions.
 Display array items – We can use interpolation along
with ngFor directive to display an array of items.

Property Binding
 Property binding is a one-way mechanism that lets you set the
property of a view element.
 It involves updating the value of a property in the component and
binding it to an element in the view template.
 Property binding uses the [] syntax for data binding

Event Binding
 In Angular event binding is used to handle the events raised by the
user actions like button click, mouse movement, keystrokes, etc.
 When the DOM event happens at an element(e.g. click, keydown,
keyup), it calls the specified method in the particular component.
 Using Event Binding we can bind data from DOM to the component
and hence can use that data for further purposes.

Two- way Binding


 In one-way data binding any change in the template (view) were
not be reflected in the component TypeScript code.
 To resolve this problem, Angular provides two-way data binding.
 The two-way binding has a feature to update data from component
to view and vice-versa.
 In two-way databinding, automatic synchronization of data happens
between the Model and the View. Here, change is reflected in both
components. Whenever you make changes in the Model, it will be
reflected in the View and when you make changes in View, it will be
reflected in Model.
 Angular's two-way binding syntax is a combination of square
brackets and parentheses, [()]. The [()] syntax combines the
brackets of property binding, [], with the parentheses of event
binding, ()
 Two-way data binding can be achieved using a ngModel directive in
Angular.
 To use ngModel first add FormsModule from angular/forms into
module.

Angular Forms

 Angular supports two design approaches for interactive forms.


 You can build forms by writing templates using
Angular template syntax and directives with the form-specific
directives and techniques described in this tutorial, or you can
use a reactive (or model-driven) approach to build forms.
 Template-driven forms are suitable for small or simple forms,
while reactive forms are more scalable and suitable for complex
forms.

Template Driven Forms


 In Template Driven Forms we specify behaviours/validations using
directives and attributes in our template.
 All things happen in Templates hence very little code is required in
the component class.
 This is different from the reactive forms, where we define the logic
and controls in the component class.

The Template-driven forms

1. The form is set up using ngForm directive


2. controls are set up using the ngModel directive
3. ngModel also provides the two-way data binding
4. The Validations are configured in the template via directives

Template-driven forms are

1. Contains little code in the component class


2. Easier to set up

While they are


1. Difficult to add controls dynamically
2. Unit testing is a challenge
 Once, we have a form with few form elements, the angular
automatically converts it into a Template-driven form.
 This is done by the ngForm directive.
 The ngForm directive is what makes the Angular template-driven
forms work.
 But we do not need to add it explicitly.
 Angular adds it automatically. When we include FormsModule, the
Angular is going to look out for any <form> tag in our HTML
template.
 Angular does this via ngForm directive. ngForm directive
automatically detects the <form> tag and automatically binds to it.

The ngForm does the following


1. Binds itself to the <Form> directive
2. Creates a top-level FormGroup instance
3. CreatesFormControl instance for each of child control, which
has ngModel directive.
4. CreatesFormGroup instance for each of the NgModelGroup directive.

 The FormControl is the basic building block of the Angular Forms.


 It represents a single input field in an Angular form.
 The Angular Forms Module binds the input element to a FormControl.
 We use the FormControl instance to track the value, user interaction
and validation status of an individual form element.
 Each individual Form element is a FormControl.
 All form elements in our HTML template. we need to bind them
to FormControl instance. We do this by using the ngModel directive.
 Like #firstName=”ngModel”.

Reactive Forms
 Reactive forms (also known as Model-driven forms) are one of the
two ways to build Angular forms.
 Reactive forms are forms where we define the structure of the form
in the component class. i,e we create the form model with Form
Groups, Form Controls, and Form Arrays.
 We also define the validation rules in the component class.
 Then, we bind it to the HTML form in the template.
 This is different from the template-driven forms, where we define
the logic and controls in the HTML template.

To use reactive forms


1. Import ReactiveFormsModule
2. Create Form Model in component class using Form Group, Form
Control & Form Arrays
3. Create the HTML Form resembling the Form Model.
4. Bind the HTML Form to the Form Model

 The FormGroup, FormControl & FormArray are the three building blocks
of the Angular Forms.
 FormControl encapsulates the state of a single form element in our
form.
 It stores the value and state of the form element and helps us to
interact with them using properties & methods.
 FormGroup represents a collection of form Controls. It can also
contain form groups and form arrays.

Structural Directives
ngIf Statement
A structural directive that conditionally includes a template based on the
value of an expression coerced to boolean.
When the expression evaluates to true, Angular renders the template
provided in a then clause, and when false or null, Angular renders the
template provided in an optional else clause.
The default template for the else clause is blank.
Eg:
Using property binding
1. Simple If
<ng-template [ngIf]="n1>0">
<h1>{{n1}} is greater than zero</h1>
</ng-template>
2. If-Else
<ng-template [ngIf]="n1>0" [ngIfElse]="blk">
<h1>{{n1}} is greater than zero</h1>
</ng-template>

<ng-template #blk>
<h1>{{n1}} is less than zero</h1>
</ng-template>

3. If-Then-Else
<ng-template [ngIf]="n1>0" [ngIfThen]="thenblk"
[ngIfElse]="elseblk"></ng-template>
<ng-template #thenblk>
{{n1}} is greater than zero
</ng-template>

<ng-template #elseblk>
<ng-template [ngIf]="n1===0" [ngIfElse]="else1">
<h1>{{n1}} is equal to zero</h1>
</ng-template>
<ng-template #else1>
<h1>{{n1}} is less than zero</h1>
</ng-template>
</ng-template>

Dependency Injection(DI)
 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
 The paradigm exists throughout Angular.
 It keeps code flexible, testable, and mutable.
 Classes can inherit external logic without knowing how to create it.
 Any consumers of those classes also do not need to know anything.
 Services are a key benefactor of DI. They rely on the paradigm
for injection into various consumers.
 Angular's DI framework provides dependencies to a class upon
instantiation. You can use Angular DI to increase flexibility and
modularity in your applications.
 The advantage of dependency injection design pattern is to divide
the task among deferent services. The client service will not create
the dependent object itself rather it will be created and injected by
an Angular injector.

Providers

 A provider is an instruction to the DI system on how to obtain a


value for a dependency. Most of the time, these dependencies are
services that you create and provide.
 Providing a service

$ ng generate service User


 The main idea behind a service is to provide an easy way to share
code and data between components. Using dependency injection
you can control how the service instances are shared

 This is the class with specific purpose


 This command creates the following UserService skeleton:

User.service.ts

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

@Injectable({

providedIn: 'root', //injectable in every where in root

})

export class UserService {

Service Scope
 You can now inject UserService anywhere in your application.
 The service itself is a class that the CLI generated and that's
decorated with @Injectable.
 Why we need services
o Share data
o Implement application logic
o External interaction

Provide Scope

 When you add a service provider to the root application injector, it’s
available throughout the app.
 You should always provide your service in the root injector unless
there is a case where you want the service to be available only if
the consumer imports a particular @NgModule).

HttpClient

Synchronous Communication
 In synchronous programs, if you have two lines of code (L1 followed
by L2), then L2 cannot begin running until L1 has finished
executing.
 You can imagine this as if you are in a line of people waiting to buy
train tickets. You can't begin to buy a train ticket until all the people
in front of you have finished buying theirs
 Similarly, the people behind you can't start buying their tickets until
you have bought yours.

Asynchronous Communication

 In asynchronous programs, you can have two lines of code (L1


followed by L2), where L1 schedules some task to be run in the
future, but L2 runs before that task completes.
 Example: You can imagine as if you are eating at a sit-down
restaurant. Other people order their food. You can also order your
food. You don't have to wait for them to receive their food and
finish eating before you order. Similarly, other people don't have to
wait for you to get your food and finish eating before they can
order. Everybody will get their food as soon as it is finished cooking.
 In a real app, we need to call the web service from the server,
which is an inherently an asynchronous service call.
 Many JavaScript developers should be familiar with using Promises
to load data asynchronously.
 In our previous app, service containing all are synchronous
signatures

Http Communication
 Observables are a more feature-rich system, which emit data in
packets.
 A single Observable object can emit a single packet of data, or can
emit a stream containing multiple discrete packets.
 Other objects can subscribe to these Observables and run a callback
each time data is emitted.
 The Observable classes in Angular are provided by the ReactiveX
library.

HttpClient
 Most front-end applications communicate with backend services
over the HTTP protocol.
 The HttpClient in @angular/common/http offers a simplified client
HTTP API for Angular applications that rests on the XMLHttpRequest
interface exposed by browsers.
 The HttpClient in @angular/common/http offers a simplified client
HTTP API for Angular applications that rests on the XMLHttpRequest
interface exposed by browsers.
 Using HttpClient we can perform CURD operations using get(),
post(), put(), and delete() methods.

Angular Routing

 In Single Page Applications only one page is requested from the


server, it provides multiple views by dynamically rewriting the
current page rather than loading the new pages from server.
 Router is an important entity in Angular and in most of the front
end frameworks. It is the code responsible for organizing an
application into multiple views. The router will display the home
page when the application is loaded first, and it allows navigation
based on request.
 Angular is a component based application, a screen view is
implemented by one or more components. Routing in angular is
referred to as component routing because the router routes each
component to a specific URL.
 Route is an object, which provides information about which
component maps to a specific path. Path is a string that specifies
where exactly the resource you want to access is located.
 In its current state, our web application does not take the browser
URL into account.
 We access our application through one URL such as
http://localhost:4200 and our application is not aware of any other
URLs such as http://localhost:4200/todos.
 Most web applications need to support different URLs to navigate
users to different pages in the application. That’s where a router
comes in.
How angular router works
 When a user navigates to a page, Angular Router performs the
following steps in order:
o it reads the browser URL the user wants to navigate to
o it applies a URL redirect (if one is defined)
o it figures out which router state corresponds to the URL
o it runs the guards that are defined in the router state.
o it resolves the required data for the router state.
o it activates the Angular components to display the page
o it manages navigation and repeats the steps above when a
new page is requested.

Route Definition Object


 The Routes type is an array of routes that defines the routing for
the application.
 This is where we can set up the expected paths, the components we
want to use and what we want our application to understand them
as.
 Each route can have different attributes; some of the common
attributes are:
o path - URL to be shown in the browser when application is on
the specific route.
o component - component to be rendered when the application
is on the specific route.
o redirectTo - redirect route if needed; each route can have
either component or redirect attribute defined in the route.
o pathMatch - optional property that defaults to 'prefix';
determines whether to match full URLs or just the beginning.
When defining a route with empty path string set pathMatch
to 'full', otherwise it will match all paths..
o children - array of route definitions objects representing the
child routes of this route

Controlling access to or from a Route


 To control whether the user can navigate to or away from a given
route, use route guards.
 we may want some routes to only be accessible once the user has
logged in or accepted Terms & Conditions. We can use route guards
to check these conditions and control access to routes.
 We can use route guards to check these conditions and control
access to routes.
 Route guards can also control whether a user can leave a certain
route.
 In order to use route guards, we must register them with the
specific routes we want them to run for.
 For example, say we have an accounts route that only users that
are logged in can navigate to. This page also has forms and we
want to make sure the user has submitted unsaved changes before
leaving the accounts page.

Component Interaction

 The parallel component can't share data.


 It only possible with parent and child.
 Pass data from parent to child with input binding
Bind data downword with @Input() Parent
| \
| \
Child1 Child2
 Sending data from Child to Parent component
o Use events to data Upwords with @Output() and
EventEmitter’s emit() method.

Pipes
Pipes are simple functions to use in template expressions to accept an
input value and return a transformed value.
Pipes are useful because you can use them throughout your application,
while only declaring each pipe once.
Pipes are denoted by {{ | }}.
There are two types of pipes
1. Built-in pipes
2. Custom pipes (User defined pipes)

Built-in pipes
 Currency pipe:- Transforms a number to a currency string,
formatted according to locale rules.
 Decimal pipe- Transforms a number into a string with a decimal
point, formatted according to locale rules.
 Date Pipe- Formats a date value according to locale rules.
 UpperCase pipe- Transforms text to all upper case.
 LowerCase Pipe- Transforms text to all lower case.
 Slice pipe- creates a new array or string from the given array or
string respectively. Slice pipe uses slice keyword with pipe
operator.
 Json pipe- convert an object to JSON format, and displays the
string in both formats for comparison.
Custom pipes
To create custom pipe following command is use
ng generate pipe <pipeName>
Eg:
ng generate pipe palindromString
above command will create pipe called as palindromString with
transform() function. We have to write logic inside transform function.

You might also like