Angular Notes
Angular Notes
Angular Notes
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.
Installation
node --version
then check npm version using following command
npm –v
here, ng is the CLI application used to create, manage and run Angular
Application. It written in JavaScript and runs in NodeJS environment.
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)
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.
Angular Forms
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.
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
User.service.ts
@Injectable({
})
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
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
Component Interaction
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.