ngula
r
WebApp Development using Angular 8/9
WHAT IS
ANGULA
R?
Angular is an app-design
framework and development
platform for creating efficient and
sophisticated single-page apps.
WHY
USE
ANGULA
R?
Angular is a structural framework for dynamic web apps. It lets you use HTML as
your template language and lets you extend HTML's syntax to express your
application's components clearly and succinctly. Angular's data binding and
dependency injection eliminate much of the code you would otherwise have to write.
And it all happens within the browser, making it an ideal partner with any server
technology.
WHAT IS
A
WEBAPP
?
A web application is a software or program which is accessible using any web
browser. Its frontend is usually created using languages like HTML, CSS, Javascript,
which are supported by major browsers. While the backend could use any
programming stack like LAMP, MEAN, etc.
WHY DO YOU
NEED
• A WEBSITE?
An effective method to showcase your products and services.
• Developing a site helps you to create your social proof.
• Helps you in branding your business.
• Helps you to achieve your business goals.
• Allows you to increase your customer support.
WHY DO YOU
NEED
• A WEBAPP?
Compared to desktop applications, web applications are easier to maintain by as they use the same
code in the entire application. There are no compatibility issues.
• Web applications can be used on any platform: Windows, Linux, Mac… as they all support modern
browsers.
• Mobile App store approval not required in web applications.
• Released any time and in any form. No need to remind users to update their applications.
WHY DO YOU
NEED
• A WEBAPP?
You can access these web applications 24 hours of the day and 365 days a year from any PC.
• You can either make use of the computer or your mobile device to access the required data.
• Web applications are a cost-effective option for any organization.
• Web-Based Apps are Internet-enabled apps that are accessed through the mobile's web browser.
Therefore, you don't require to download or install them.
HOW DOES
ANGULAR
BENEFIT YOU?
• Angular is supported by Google, which makes for a dependable, trustworthy program that is most
likely to keep up with Google’s occasional updates and announcements.
• Angular has detailed documentation making it a reliable framework backed by a robust amount of
helpful information and answers to common questions.
HOW DOES
ANGULAR
BENEFIT YOU?
• With Angular elements and modules, this framework is designed to be fully customizable, giving more
power to the developer and designer.
• Angular provides a great selection of third-party integrations that can be added to the framework with
ease. This gives developers even more tools to improve the overall form and function of their product.
CONS OF
USING
ANGULAR
• One of the major drawbacks to using Angular is the platform’s limited SEO options and poor
accessibility for search engine crawlers.
• Unless you’re working on a project of appropriate size and complexity, Angular can easily weigh you
down.
INSTALLAT
ION
Installation of all the pre requisites and the Angular CLI to get started with an Angular Project.
INSTALLING
NODEJS
To Install NodeJS, download the recommended
version from the official website and go through
the installation procedure.
INSTALLING
ANGULAR CLI
npm install -g @angular/cli
Run the Command shown to install Angular CLI
Switching to Visual Studio
Code
PROJECT
STRUCTUR
E
DEV
TOOLS
An Intro to all the development tools we will be using during the workshop.
VISUAL STUDIO
CODE
To install Visual Studio code, download the
latest version from [Link] and
follow the installer.
VSCODE
EXTENSIONS
The Angular Language Service extension for VS
Code provides a rich editing experience for
Angular templates.
VSCODE
EXTENSIONS
The Live Share extension for VS Code enables
us to collaboratively edit and debug with
others in real time.
BROWSER DEV
TOOLS
The Live Share extension for VS Code enables
us to collaboratively edit and debug with
others in real time.
USING
ANGULAR
CLI
Using the Angular CLI to create a new project, component, service
and a conventional Angular project structure.
BASIC CLI
ng help
COMMANDS
Lists available commands and their short
descriptions.
Creates a new workspace and an initial Angular app.
ng new TestApp
Builds and serves your app, rebuilding on file
ng serve -o changes.
Updates your application and its dependencies.
ng update
BASIC CLI
ng generate
COMMANDS
Generates and/or modifies files based on a
schematic.
Compiles an Angular app into an output directory
ng build named dist/ at the given output path.
Outputs Angular CLI version.
ng version
ng update
MODUL
ES
A Module is a collection of services, directives, controllers, filters, and configuration information.
MODUL
ES
In Angular, a module is a mechanism to group components, directives, pipes and services that are related,
in such a way that can be combined with other modules to create an application.
An Angular application can be thought of as a puzzle where each piece (or each module) is needed to be
able to see the full picture.
MODUL
ES
Another analogy to understand Angular modules is classes.
• The public methods are the API that other parts of our code can use to interact with it.
• The private methods are implementation details that are hidden.
In the same way, a module can export or hide components, directives, pipes and services.
MODUL
ES
import { NgModule } from '@angular/core'; To be able to define modules, we
have to use the NgModule
@ NgModule({ decorator.
imports: [ ... ],
In the example, we have turned
declarations: [ ... ], the class AppModule into an
bootstrap: [ ... ] Angular module just by using the
}) NgModule decorator.
export class AppModule { }
The NgModule decorator requires
at least three properties: imports,
declarations and bootstrap.
COMPONE
NTS
The core concept of any Angular application is the component.
COMPONE
NTS
The core concept of any Angular application is the component. In effect, the whole application can be
modeled as a tree of these components.
According to the Angular team, A component controls a patch of screen real estate that we could call a
view, and declares reusable UI building blocks for an application.
DEFINING
COMPONENTS
import { Component } from '@angular/core'; To define a component in Angular,
we create a class with our
@ Component({ application logic and add a
Component decorator to it.
selector: 'app-hello',
template: `<p>Hello World!</p>` To use this component, we use the
}) selector inside a HTML file or
export class HelloComponent { another template.
constructor() {}
}
TEMPLATING AND
STYLING
<div class="jumbotron"> Creating a component in Angular
essentially gives us a new
<h1 class="display-4">Hello, world!</h1> reusable UI which we can make
use of using the selector.
<p class="lead">This is some </p>
<hr class="my-4"> These selectors behave the same
way as HTML tags do, therefore
<p>It uses utility classes for typography and spacing enabling us to nest them.
to space content out within the larger container.</p>
<a class="btn btn-primary btn-lg" href="#"
role="button">Learn more</a>
</div>
DATA
BINDING
Data binding in AngularJS is the synchronization between the model and the view. When data in the model
changes, the view reflects the change, and when data in the view changes, the model is updated as well.
DATA
BINDING
String Property Two-Way Data
Event Binding
Interpolation Binding Binding
STRING
INTERPOLATION
This adds the value of a property from the component.
String Interpolation is a one-way
databinding technique which is used to output the
data from a TypeScript code to HTML template (view). <li>
Name: {{ [Link] }}
It uses the template expression in double curly </li>
braces to display the data from the component to the <li>
view. Email: {{ [Link] }}
</li>
String interpolation adds the value of a property from
the component.
PROPERTY
BINDING
With property binding, the value is passed from the
component to the specified property, which can often
be a simple HTML attribute.
Property Binding is also a one-way data <input type = "'email" [value]
binding technique where we bind a property of a = "[Link]">
DOM element to a field which is a defined property in
our component TypeScript code. <div [[Link]-color] =
"selectedColor">
Property binding is preferred over string interpolation
because it has shorter and cleaner code.
<div [class.
selected]="isSelected">
EVENT
BINDING
When a specific DOM event happens (eg.: click,
change, keyup), call the specified specified method in
the component.
In the example, the cookBiriyani() method from the <button
component is called when the button is clicked. (click)="clickHandler()">
</button>
The event name between ( ) must be in the list of
HTML DOM events. <input
(change)="changeHandler()"
placeholder="Enter your name" />
TWO-WAY DATA
BINDING
This is a term coined from merging property binding
with event binding: [( )] to gain the two-way binding
power.
With this communication is two-way from the Model <input type="email"
to the View and View to the Model. [(ngModel)]="[Link]" />
You can change the Model data from the View and
also from the Model and both will reflect the changes.
In this example, the [Link] data property is used as
the value for the input, but if the user changes the
value, the component property gets updated
automatically to the new value
DIRECTI
VES
The Angular directives are used to manipulate the DOM. By using Angular directives, you can change the
appearance, behavior or a layout of a DOM element.
DIRECTI
VES
Directives are a core Angular feature. Directives in Angular are JavaScript functions that manipulate and
add behaviors to HTML DOM elements. Directives can be very simplistic or extremely complicated.
You can define your own directives to attach custom behavior to elements in the DOM.
There are three kinds of directives in Angular:
• Component Directives
• Structural Directives
• Attribute Directives
COMPONENT
@Component({
DIRECTIVES A component directive has a
controller and template. The
decorator contains the
selector: 'app-my-input’, metadata for the selector and
template: ` <app-bank-account template. The controller
bankName="RBC" account-id="4747"> </app- consists of a class that
bank-account> ` contains properties and
}) methods that can be used to
manipulate the view and
content templates. It is used
export class MyExampltComponent { in main class which tells us
} about how component should
be processed, instantiated at
runtime.
STRUCTURAL
DIRECTIVES
• *ngIf Directive: The ngIf allows us to Structural directives start with a * sign.
Add/Remove DOM Element. These directives are used to manipulate and
• *ngSwitch Directive: The *ngSwitch change the structure of the DOM elements.
allows us to Add/Remove DOM Element. For example, *ngIf directive, *ngSwitch
It is similar to switch statement of C#. directive, and *ngFor directive.
• *ngFor Directive: The *ngFor directive is
used to repeat a portion of HTML
template once per each item from an
iterable list (Collection).
ATTRIBUTE
DIRECTIVES
• ngClass Directive: The ngClass directive Attribute directives are used to change the
is used to add or remove CSS classes to look and behavior of the DOM elements.
an HTML element. For example: ngClass directive, and ngStyle
directive etc.
• ngStyle Directive: The ngStyle directive
facilitates you to modify the style of an
HTML element using the expression.
LIFECYCLE
HOOKS
A feature that lets Developers tap into key moments of the lifecycle of an Angular Application by implementing
one or more of the lifecycle hook interfaces in the Angular core library.
LIFECYCLE
HOOKS
Every component has a lifecycle managed by Angular. Angular creates and renders components along
with their children, checks when their data-bound properties change, and destroys them before removing
them from the DOM. Angular offers lifecycle hooks that provide visibility into these key life moments and
the ability to act when they occur.
LIFECYCLE
HOOKS
• ngOnChanges() • ngAfterContentChecked(
• ngOnInit() )
• ngDoCheck() • ngAfterViewInit()
• ngAfterContentInit() • ngAfterViewChecked()
• ngOnDestroy()
LIFECYCLE
HOOKS
SERVI
CES
A service is a special class with a narrow, well-defined purpose encompassing any value,
function, or feature that an app needs
SERVI
CES
A service is a special class with a narrow, well-defined purpose encompassing any value, function, or
feature that an app needs
Angular distinguishes components from services to increase modularity and reusability.
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.
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.
SERVI
CES
export class Logger {
Here's an example of a service class that logs to
log(msg: any){
the browser console. [Link](msg);
}
A service can depend on another service. This is }
achieved using Dependency Injection.
DEPENDE
NCY
INJECTIO
N
Dependency Injection is passing dependencies to other objects or framework.
DEPENDENCY
INJECTION
Dependency Injection is passing dependency to other objects or framework( dependency injector).
Dependency injection makes testing easier. The injection can be done through constructor.
DI in an angular framework is used to provide new components with services or other things they need.
Services can be injected in a component, giving the component access to the specific class.
DEPENDENCY
INJECTION
For any dependency that you need in your app, you must register a provider with the app's injector, so that
the injector can use the provider to create new instances.
When Angular creates a new instance of a component class, it determines which services or other
dependencies that component needs by looking at the constructor parameter types.
When Angular discovers that a component depends on a service, it first checks if the injector has any
existing instances of that service. If a requested service instance doesn't yet exist, the injector makes one
using the registered provider, and adds it to the injector before returning the service to Angular.
PIP
ES
A way to write display-value transformations that you can declare in your HTML.
PIP
ES
A pipe takes in data as input and transforms it to a desired output.
You can write pipes and use them in your HTML code, much like styles and that would enable us to
transform our data depending on our needs.
In the example, we are using the uppercase pipe to <p>Hey {{ name | uppercase }},
display the name in complete uppercase. We do Welcome!</p>
not change the data but instead, we transform it
into the format we desire using pipes.
BUILT IN
PIPES
• Lowercase pipe • Json pipe
• Uppercase pipe • Percent pipe
• Date pipe • Decimal pipe
• Currency pipe • Slice pipe
PARAMETERIZING
PIPES
A pipe can accept any number of optional parameters to fine-tune its output.
To add parameters to a pipe, follow the pipe name with a ‘:’
In the example, we are passing a parameter to the <p>Date is {{ todayDate | date:
DatePipe using the ‘:’ and that transforms the ‘shortDate’ }}</p>
‘todayDate’ variable into a simpler format and
displays it in our HTML.
CHAINING
MULTIPLE PIPES
We can chain multiple pipes together. This particularly helps in scenarios where we need to associate
more than one pipe that needs to be applied, and the final output will be transformed with all the pipes
applied. The workflow or chains will be triggered and apply the pipes one after another.
In the example, we are using the default DatePipe <p>Date is {{ todayDate | date |
and the UppercasePipe together to transform the uppercase }}</p>
output.
ROUTI
NG
The router enables navigation from one view to the next.
ROUTI
NG
It is used to show the user different components and data to the user based on where the user is in the
application.
You can bind the router to links on a page and it will navigate to the appropriate application view when the
user clicks a link.
You can navigate imperatively when the user clicks a button, selects from a drop box, or in response to
some other stimulus from any source.
ROUTI
NG
The Angular Router borrows from the model of a browser. It can interpret a browser URL as an instruction
to navigate to a client-generated view.
The browser is a familiar model of application navigation:
• Enter a URL in the address bar and the browser navigates to a corresponding page.
• Click links on the page and the browser navigates to a new page.
• Click the browser's back and forward buttons and the browser navigates backward and forward
through the history of pages you've seen
ROUTER
LINKS
The routerLink directive lets you link to specific routes in your app.
<nav>
<a routerLink="/home">Home </a>
<a routerLink="/about">About </a>
</nav>
ROUTER
PARAMETERS
Angular lets us pass parameters to our routes. This enables us to navigate to different views with identical
URL structure.
{ path: 'workshop/:id', component: WorkshopComponent}
NESTED
ROUTES
To create nested routing , we must have a parent and a child route.
const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'artist/:artistId', component: ArtistComponent,
children: [
{ path: '', redirectTo: 'tracks' },
{ path: 'tracks', component: ArtistTrackListComponent },
{ path: 'albums', component: ArtistAlbumListComponent },
]},
];
WILDCARD
ROUTES
When we enter a URL to a route that hasn’t been defined yet, the router throws and error and crashes the
app.
A wildcard route is used to intercept invalid URLs.
A wildcard route has a path consisting of two asterisks. It matches every URL. The router will select this
route if it can't match a route earlier in the configuration.
The router selects the route with a first match wins strategy. Wildcard routes are the least specific routes
in the route configuration. Be sure it is the last route in the configuration.
WILDCARD
ROUTES
To create a wildcard route, we define a path with two asterisks.
const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full', },
{ path: '', component: PageNotFoundComponent },
];
ROUTE
GUARDS
At the moment, any user can navigate anywhere in the application anytime. That's not always the right
thing to do.
• Perhaps the user is not authorized to navigate to the target component.
• Maybe the user must login (authenticate) first.
• Maybe you should fetch some data before you display the target component.
• You might want to save pending changes before leaving a component.
• You might ask the user if it's OK to discard pending changes rather than save them.
ROUTE
GUARDS
A guard's return value controls the router's behavior:
• If it returns true, the navigation process continues.
• If it returns false, the navigation process stops and the user stays put.
• If it returns a UrlTree, the current navigation cancels and a new navigation is initiated to the UrlTree
returned.
ROUTE
GUARDS
The AdminComponent can only be accesed if AuthGuard returns true.
import { AuthGuard } from '../auth/[Link]';
const adminRoutes: Routes = [
{ path: 'admin', component: AdminComponent, canActivate: [AuthGuard] }
];
ROUTE
GUARDS
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
return true;
}
}
HTTP
MODULE
Angular’s way of letting us communicate with backend services.
HTTP
CLIENT
Every app needs backend services in order to provide the complete app experience. Backend services
could be anything from fetching data from a remote server or authenticating a user from the database.
Front-end frameworks like Angular use HTTP Protocol to communicate with backend services. Modern
browsers support two different APIs for making HTTP requests: the XMLHttpRequest interface and
the fetch() API.
HTTP
CLIENT
The HttpClient in Angular offers a simplified client HTTP API for Angular applications that rests on
the XMLHttpRequest interface exposed by browsers.
Additional benefits of HttpClient includes testability features, typed request and response objects,
request and response interception, Observable API's, and streamlined error handling.
HTTP
CLIENT
To use the HTTP Client, we have to first import the HttpClientModule into the AppModule.
import { HttpClientModule } from '@angular/common/http';
Having imported HttpClientModule, we can inject the HttpClient into an application class as shown.
export class ConfigService {
constructor(private http: HttpClient) { }
}
HTTP GET
REQUEST
The Http GET method is used to retrieve information from the given server using a given URI. Requests
using the GET method should only retrieve data and should not have any other effect on the data.
getConfig() {
return [Link]('[Link]
}
HTTP POST
REQUEST
A POST request is used to send data to the server, for example, customer information, file upload, etc. A
POST request is usually sent as a response to submitting Forms.
addDish (dish: Dish): Observable<Dish> {
return [Link]<Dish>('[Link]
dish, httpOptions);
}
THANKS FOR
YOUR ATTENTION