0% found this document useful (0 votes)
14 views29 pages

Angular

Uploaded by

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

Angular

Uploaded by

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

Angular

Introduction to angular
Angular is one of the most popular javascript frameworks for building
client-side applications.

What is angular?
1. Angular is a development platform for building a single-page application for
mobile and desktop.
2. It is used for building client-side applications using HTML, CSS, and a
programming language like javascript or typescript.
3. Angular is not a programming language in itself like JavaScript.

Framework:
1. A framework is like a platform for developing software applications.
2. A framework can have pre-defined classes and functions that can be re-used to
add several functionalities, which otherwise we would have to write from scratch
on our own.
3. A framework is a collection of pre-defined classes and methods that provide APIs
for performing different operations when used in an application.

Single page application


1. A single-page application is a web application, that has only one HTML page.
When we navigate around, only the content of that HTML page changes. The
page itself never changes.

Advantage of SPA
1. Since we are using JavaScript to change the page's content, it is much faster.
Here we are not reaching out to the server to request a new piece of HTML data,
every time we navigate to a different URL.
2. This allows us to create an application that is fast and reactive.

Limitations of JavaScript / JQuery


1. Vanilla javascript or jQuery code becomes hard to maintain and we will need a
way to structure our application properly.
2. Many applications built using vanilla javascript / JQuery are hard to test.
3. We will have to write some functionalities from scratch when using JavaScript /
JQuery.
Angular

Advantages of using angular:


1. Angular gives our application a clean and loosely coupled structure that is easy
to understand & maintain.
2. It brings a lot of utility codes that can be reused in a lot of applications.
Especially, when dealing with user navigation & browser history.
3. Applications built with angular are more testable.

Different versions of angular?


1. Angular JS was not designed with the needs of today's applications.
2. Angular 2 was completely rewritten from the ground up.
3. It fixed all the issues that Angular 1 had.
4. There had not been major changes after the release of Angular 2.

Advantage of Typescript
1. Typescript is a superset of javascript.
2. Typescript has additional features feature

Interpolation & Property binding


1. Interpolation is used to just display a piece of data in HTML, such as displaying a
title or a name.
2. Property binding lets us bind a property of a DOM object, for example, the hidden
property, to some data value. This can let us show or hide a DOM element, or
manipulate the DOM in some other way.

Two-way Data Binding


1. Two-way data binding is a combination of property binding & event binding.

Directives
1. Component Directive
a. A component directive is the angular component. It is a directive with a
template.

2. Attribute Directive
a. Attribute directive is used to change the appearance of the behavior of a
DOM element.
b. <div changetoGreen>Some Content</div>
Angular

c. ngStyle
d. ngClass
3. Structural Directive
a. ngIf, ngFor, ngSwith
b. <div *ngIf>Some Content</div>
c. Structural directives add or remove a DOM element on the webpage.

ngFor Directive
1. Angular ngFor directive iterates over a collection of data like an array, list, etc.,
and creates an HTML element for each of the items from an HTML template.
2. The ngFor directive is used to repeat a portion of the HTML template once per
each item for an itterable list.
3. The ngFor directive is a structural directive. It manipulates the DOM by
adding/removing elements from the DOM.

ngIf Directive
1. Angular ngIf directive is a structural directive that is used to completely add or
remove a DOM element from the webpage based on a given condition.
2. The ngIf directive is used to add or remove a DOM element from the webpage
based on a given condition.
3. The ngIf directive is a structural directive. It manipulates the DOM by
adding/removing elements from the DOM.

ngStyle Directive
1. The ngStyle directive is an attribute directive that allows us to set many inline
styles of an HTML element using expression.
2. The ngStyle directive is used to set a CSS style dynamically on an HTML
element based on a given TypeScript expression.
3. The ngStyle directive is an attribute directive. It changes the look or behavior of
an HTML element.

ngClass Directive
1. The ngClass directive is used to set a CSS class dynamically on an HTML
element based on a given Typescript expression.
2. The ngClass directive is an attribute directive. It changes the look or behavior of
an HTML element.
Angular

Input Decorator
1. Custom property binding is when we bind properties of a component class to
some TypeScript expression.
2. We can pass data from a parent component to its child component using the
@Input decorator.

Template Reference Variable


1. A template reference variable is a variable that stores a reference to a DOM
element, Component, or Directive on which it is used.

ViewChild() Decorator
1. The ViewChild decorator is used to query and get a reference of the DOM
element in the component. It returns the first matching element.

ViewChildren Decorator
1. The ViewChildren decorator is used to get a reference to the list of DOM
elements from the view template in the component class. It returns all the
matching elements.

Ng-template
1. The ng-template is an Angular element that wraps an HTML snippet. This HTML
snippet acts and can be used like a template and can be rendered in the DOM.

Ng-container
1. The ng-container is a special Angular element that can hold structural directives
without adding new elements to the DOM.

ContentChild Decorator
1. The @ContentChild decorator is used to access a reference of a DOM element,
component, or directive from the projected content into the child component
class.
Angular

ContentChildren Decorator
1. The @ContentChildren decorator is used to access a reference of all the DOM
elements, components, or directives from the projected content in the child
component class based on a given selector.

Component Initialization
1. When the Angular application starts, it first creates and renders the root
component.
2. Then it creates and renders its children and their children, in this way, it forms a
tree of components.
3. Once Angular loads the component, it starts the process of rendering the view.
To do that, it needs to check the input properties, evaluate the data bindings &
expressions, render the projected content, etc.
4. Angular then also removes the component from the DOM when it is no longer
needed.
5. And Angular lets us know when these events happen, using Angular lifecycle
hooks.
6. The Angular life cycle hooks are the methods that angular invokes on a directive
or a component, as it creates, changes, and destroys them.
a. ngOnChanges
b. ngOnInit
c. ngDoCheck
d. ngAfterContentInit
e. ngAfterContentChecked
f. ngAfterViewInit
g. ngAfterViewChecked
h. ngDestroy

ngOnChanges Hook
1. Change detection in Angular is a mechanism by which, Angular keeps the view
template in sync with the component class.
a. Whenever the @input property of a component changes
b. Whenever a DOM event happens. E.g. click or change
c. Whenever a timer event happens use setTimeOut() / setInterval().
d. Whenever an HTTP request is made.
2. The ngOnChanges Hook gets executed at the start when a new component is
created and its input-bound properties are updated.
3. The ngOnChanges hook also gets executed every time the input-bound
properties of the component change.
Angular

4. The ngOnChanges hook is not raised if the change detection cycle does not find
any changes in the input properties value.

ngOnInit Hook
1. Angular raises the ngOnInit hook after it creates the component and updates its
input properties. This hook is raised after ngOnChanges.
2. The ngOnInit hook is fired only once i.e. during the first change detection cycle.
After that, if the input property changes, this hook does not get called.
3. By the time ngOnInit gets called, none of the child components or projected
contents of view are available at this point. Hence any property decorated with
@ViewChild, @ViewChildren, @ContentChild, or @ContentChildren will not be
available to use.

ngDoCheck Hook
1. Angular invokes the ngDoCheck hook during every change detection cycle. This
hook is invoked even if there is no change in input-bound properties.
2. For example: The ngDoCheck lifeCycle hook will run if you click a button on a
webpage, which does not do anything. But still, it's an event so the change
detection cycle will run and execute ngDocheck hook.
3. Angular invokes the ngDoCheck lifecycle hook after the ngOnChanges &
ngOnInit hooks.
4. You can use this hook to implement a custom change detection, whenever
angular fails to detect any change made to input bound properties.
5. The ngDoCheck hook is also a great place to use when you want to execute
some code on every change detection cycle.

ngAfterContentInit Hook
1. The ngAfterConentInit lifeCycle hook is called after the components' projected
content has been fully initialized.
2. Angular updates the properties decorated with @ContentChild &
@ContenetChildren decorator just before this hook is raised.
3. This lifeCycle hook gets called only once, during the first change detection cycle.
After that, if the projected content changes, this lifecycle hook will not get called.

ngAfterContentChecked Hook
1. The ngAfterContentChecked lifecycle hook is called during every change
detection cycle after Angular has finished initializing and checking projected
content.
Angular

2. Angular also updates the properties decorated with @ContentChild &


@ContentChildren decorator, before raising, the ngAfterContentChecked hook.
3. Angular raises this hook even if there is no projected content in the component.
4. The ngAfterContentInit hook is called after the projected content is initialized.
ngAfterContentChecked is called whenever the projected content is initialized,
checked & updated.
5. Note: The ngAfterContenetInit & ngAfterContentChecked are component-only
hooks. These hooks are not available for directives.

ngAfterViewInit Hook
1. The ngAfterViewInit is called after the components view template and all its child
components view templates are fully initialized.
2. Angular also updates the properties decorated with @ViewChild and
@ViewChildren decorator before raising this hook.
3. This hook is called during the first change detection cycle when Angular
initializes the view for the first time.
4. By the time this hook gets called for a component, all the lifecycle hook methods
of child components and directives are completely processed and child
components are completely ready.
5. Note: The ngAfterViewInit hook is also a component-only hook.

ngAfterViewChecked Hook
1. Angular fires the ngAferViewChecked hook after it checks and updates the
components view template and all its components view templates.
2. This hook is called during the first change detection cycle after the
ngAfterViewInit hook has been executed. And after that during every change
detection cycle.
3. Angular also updates the properties decorated with @ViewChild and
@ViewChildren decorator before raising this hook.
4. Note: The ngAfterViewChecked hook is component-only, It is not available for
directives.

ngOnDestroy Hook
1. Angular fires the ngOnDestroy lifecycle hook just before the component or the
directive is destroyed i.e. removed from the DOM.
2. This hook is a great place to do some cleanup work like unsubscribe from an
observable or detach event handler etc., as this hook is called right before the
component is destroyed.
Angular

3. This ngOnDestroy is the last lifecycle hook of a component & a directive.

Custom Attribute Directive


1. Component Directive
a. The component directive is the angular component. It is a directive with a
template.
b. Components
2. Attribute Directive
a. Attribute directive is used to change the appearance or behavior of a DOM
element.
b. ngStyle, ngClass
3. Structural Directives
a. The structural directive is used to add or remove a DOM element on the
webpage.
b. ngFor, ngIf

Renderer2 (Custom Directive)


1. Renderer2 allows us to manipulate the DOM without accessing the DOM
elements directly, by providing a layer of abstraction between the DOM element
and the component code.
2. Angular keeps the component & view in sync using templates, data binding and
change detection, etc. All of them are bypassed when we update the DOM
directly.
3. The DOM manipulation works only in browsers. You will not be able to use your
app on other platforms like web workers, servers for server-side rendering,
desktop or mobile apps, etc. where there is no browser.
4. The DOM APS does not sanitize the data. Hence it is possible to inject a script,
thereby, opening our app as an easy target for the XSS injection attacks.

@HostListner In Angular
1. The @HostListner decorator listens to a DOM event on the host element and it
reacts to that event by executing an event handler method.

@HostBinding In Angular
1. The @HostBinding decorator binds a host element property to a property of a
directive or a component class.
Angular

Structural Directives:

What is View Encapsulation


1. Encapsulation means hiding data and behavior from the outside world.
2. The view encapsulation is a concept or behavior in Angular, where component
CSS styles are encapsulated into the components view and do not effect the rest
of the application.
3. View Encapsulation Types: There are three types of view encapsulation in
Angular.
a. ViewEncapsulation.None
b. ViewEncapsulation.Emulated
c. ViewEncapsulation.ShadowDOM

What is Service in Angular


1. A Service in Angular is a re-usable TypeScript class that can be used in multiple
components across our Angular Application.
1. Disadvantages
a. The same code is repeated in three different component classes. We are
violating the DRY principle.
b. Component class should only be responsible for representing UI to the
user.
c. Presentation logic must be separated from business logic to make
components more maintainable.
2. Advantages
a. Services allow us to reuse a piece of code in multiple components,
wherever it is required. In this way, we avoid repeating a piece of code.
b. It allows us to separate business logic from UI logic. We write UI logic in a
component class and business logic in a service class. In this way, it
provides a separation of concern.
c. We can unit test the business logic written in a service class separately
without creating a component. Testing and debugging are easier with
services.

Dependency injection:
1. A dependency is a relationship between two software components where one
component relies on the other component to work properly.
Angular

2. Dependency injection (DI) is a technique (design pattern) using which a class


receives its dependencies from an external source rather than creating them
itself.

Disadvantage of not using Dependency Injection(DI)


1. Without dependency injection, a class is tightly coupled with its dependency. This
makes a class non-flexible. Any change in dependency forces us to change the
class implementation.
2. It makes testing in class difficult. Because if the dependency changes, the class
has to change. When the class changes, the unit test mock code also has to
change.

Advantages of using Dependency Injection (DI)


1. Dependency injection or DI keeps the code flexible, testable, and mutable.
2. Classes can inherit external logic without knowing how to create it.
3. Dependency injection benefits components, directives, and pipes.

Hierarchical Dependency Injection


1. When we provide a dependency on a component, the same instance of that
dependency is injected in the component class and all its child components and
their child components. This is called a hierarchical injection.

Dependency Override
1. When we provide a dependency on a component and we also provide a
dependency on its child component, the child component dependency instance
will override its parent component dependency instance.

Dependency injection on Root Component


1. When we provide a dependency on a root component, the same instance of that
dependency is injected into all components, directives, and services.

Module Injector
1. We can also inject a service from the module class. In that case same instance
of the dependency will be available throughout the angular application. In this
way, we implement a singleton pattern where a single instance is shared
throughout the application.
Angular

What is an Observable?
1. An Observable is a wrapper around asynchronous data. We use an observable
to handle asynchronous data.
2. Promise, Observable

What is synchronous programming?


1. JavaScript is a single-threaded programming language.
a. The code is executed line by line one after the other in the order in which
they are defined.

What is asynchronous programming?


1. Asynchronous code does not execute in single-threaded. It gets executed in the
background.
a. Asynchronous code is blocking in nature.

Promise vs Observable
1. A promise cannot handle the stream of asynchronous data. It always returns a
single value. On the other hand, we can use observables to handle a stream of
asynchronous data. It can return multiple values.
2. A Promise will certainly return data even if no code is using that data. Whereas
an observable will return data only if someone is going to use that data.
3. A promise is native to the JavaScript program. Whereas observable is not native
to javascript and is provided by the “RxJS” library.
4. Promise
a. A Promise is native to JavaScript.
b. Promise is eager. It returns the data as soon as a promise is created.
c. A promise can emit only a single value.
d. Promise has methods for success & error.
e. Promise always returns asynchronous data.
5. Observable
a. An Observable is not native to JavaScript. It is provided by a third-party
library called RxJS.
b. Observable is lazy. It only emits the data if there is a subscriber for that
observable.
c. Observables can emit single or multiple values.
d. Observables have methods for success, error, and completion.
e. An Observable can return both synchronous and asynchronous data
based on how it is implemented.
Angular

What is an Observable?
1. An Observable is a function that converts the ordinary data stream into an
observable one. You can think of observable as a wrapper around the ordinary
data stream.

Observable Pattern
1. Observable (Event Emitter) → Observer (Event Listener Subscriber) →
Handler (Event Handler)
2. Event Emitter
a. Next
b. Error
c. Completion
3. Event Listener Subscriber
a. Subscribe()
4. Event Handler
a. Next()
b. Error()
c. Completion()

Of Operator in RxJs
1. The “of” operator creates an observable from the arguments that we pass into it.
You can pass any number of arguments to of operator.
2. Each argument is emitted separately one after the other. It sends the complete
signal at the end.

The from Operator


1. The “from” operator takes a single argument which can be iterated over and
converts it into an observable.

The map Operator


1. The map operator is used to transform data emitted by source observable in
some way.
Angular

The filter Operator


1. The filter operator is used to filter data emitted by a source observable based on
a given condition.

Subjects in RxJS
1. A subject is a special type of observable that allows values to be multicasted to
many observers. Subjects are like EventEmitters.

Observable vs Subject
1. A subject is multicast. On the other hand, an Observable is unicast.

Behaviour Subject
1. A BehaviourSubject is a subject that can hold an initial value that it emits if no
new value is emitted. A BehaviourSubject emits an initial value or last emitted
value for a new subscriber.

Replay Subject
1. ReplaySubject replays old values to new subscribers when they first subscribe.
2. The ReplaySubject will store every value it emits in a buffer. It will emit them to
the new subscribers in the order it received them. You can configure the buffer
using the arguments bufferSize and window time.
3. BufferSize: No of items that ReplaySubject will keep in its buffer. It defaults to
infinity.
4. WindowTime: The amount of time to keep the value in the buffer. Default to
infinity.

Async Subject
1. AsyncSubject only passes the last emitted value to all its subscribers once the
complete method is called on it.

What is Routing
1. Routing allows us to navigate from one part of our application to another part. In
Angular, using routing, we can move from the view of one component to the view
of another component.
2. To implement routing in Angular, we use a built-in @angular/router module.
Angular

How to define Routes


1. Create a new route using the Routes array and define some route objects inside
that array.
2. Register the route using RouterModule.forRoot(routeName);
3. Use <router-outlet> where you want to render the view of the specified route
component.

NotFound Routes (Wild Card Route)


1. A wild card route is that route which matches every route path. In angular, the
wild card route is specified using ** signs.
2. NOTE: A wild card route must be specified at the end of all the defined routes.

RouterLink Directive
1. The RouterLink is a directive that binds the HTML element to a Route. When the
HTML element on which we have used the RouterLink is clicked, it will result in
navigation to that route.
2. NOTE: RouterLink directive is an attribute and we can also pass additional
parameters to it.

RouterLinkActive Directive
1. The RouterLinkActive is a directive for adding or removing classes from an
HTML element that is bound to RouteLink.
2. Using the RouterLinkActive directive, we can toggle CSS classes for active
route links based on the current router state.
3. The main use case of the RouterLinkActive directive is to highlight which route
is currently active.

RouterLinkActiveOptions Directive
1. When a child route is active, then all the parent routes are also marked as active.
In that case, routeLinkActive directive is applied to the active child route and all
its parent routes.
2. Using the RouterLinkActiveOptions directive, we can set some options for the
routerLinkActive directive. One of the options we can set is the exact property
which tells how to match the route path for styling the active route.
3. [routerLinkActiveOptions]=“{exact: true}”
Angular

Absolute Path
1. When we use a slash (“/”) before the router link path, in that case, it uses an
absolute path, and the path is directly appended to the root URL.
2. <a routerLink=”/About”>About</a>
3. URL: localhost:4200/About

Relative Path
1. When we do not use a slash (“/”) before the router link path, in that case, it uses
a relative path, and the path is appended to the currently active route.
2. For example, let’s say the currently active route is About. A link is defined in the
About page to go to the home page as shown below. If that link is clicked, the
path will be appended to the currently active route.
3. <a routerLink=”/Home”>Go to home</a>
4. URL: localhost:4200/About/Home

Relative Path (“./”)


1. When we use a dot & a slash (“./”) before the router link path, in that case, it uses
a relative path, and the path is appended to the currently active route.
2. Current Active Router Link Path: localhost:4200/Books/Author
3. <a routerLink=”./Stephen-King”>Stephen King</a>
4. URL: localhost:4200/Books/Author/Stephen-King

Relative Path(“../”)
1. When we use (“../”) before the router link path, in that case it will move one level
up and the path will be appended to the parent path.
2. Current Active Router Link Path: localhost:4200/Book/Author
3. <a routerLink=”../Stephen-King”>Stephen King</a>
4. URL: localhost:4200/Books/Stephen-King

Relative Path(“../../”)
1. When we use (“../../”) before the router link path, in that case, it will move two
levels up and the path will be appended after removing the last two paths from
the URL.
2. Current Active Router Link Path: localhost:4200/Book/Author
3. <a routerLink=”../../Stephen-King”>Stephen King</a>
4. URL: localhost:4200/Stephen-King
Angular

navigate() Method
1. Using the navigate() method, we can navigate from one route to another
programmatically. The navigate method takes an array as an argument and in
that array, we can specify route segments.
2. Let’s say, we want to navigate the user to the following route:
3. URL: localHost:4200/Books/Author/101
4. We can pass each segment of the above URL as an element of the passed array
to the navigate method.
5. this._router.navigate([‘Books’, ‘Author’, 101]);

navigateByUrl() Method
1. Using the navigateByUrl() method, we can navigate from one route to another
programmatically. The navigateByUrl method takes a string value as an
argument and that string value should contain all the route segments.
2. Let’s say, we want to navigate the user to the following route:
3. URL: localHost:4200/Books/Author/101
4. We can pass each segment of the above URL as an element of the passed array
to the navigate method.
5. this._router.navigateByUrl(‘Books/Author/101’);

Route Parameter
1. The route parameters are the dynamic part of the route whose value can change.
These parameters provide a way to pass extra information to a given route.
2. localhost:4200/Books/:id
3. localhost:4200/Books/Author/:author

Snapshot property
1. The snapshot property contains the current value of the route. If the value of
the route parameter changes after we have retrieved the value of the route, that
change will not get captured.
2. This.activeRoute.snapshot.paramMap.get(‘id’);

The paramMap Observable


1. By subscribing to the paramMap observable (or to the params observable), you
will get a notification when the value changes. Hence, you can retrieve the latest
value of the parameter and update the component accordingly.
Angular

What is a Query String?


1. Query Strings are the optional data that we can pass to a component through a
route. These query strings are added at the end of the route after a?
2. localhost:4200/Books/Author?name=stefen-king
3. localhost:4200/Products/product?id=12345&name=iphone

Route Parameter vs Query String


1. Route parameters are required and it is used by Angular router to determine the
route. Route Parameters are part of the route definition.
2. Query strings are optional data that we pass through the route. If the query
parameter is missing in the URL, then it will not stop angular from navigating to
the route.

What is a fragment?
1. A fragment in a route is a link that jumps to a section or content in the HTML
page, which contains the ID mentioned in the fragment. A fragment comes after a
# sign.
2. localhost:4200/Home#Services

What is Route Guard?


1. Angular route guards can be used to control whether the user can navigate to or
away from a route based on a given condition.

Why Route Guard?


1. Allowing the user to navigate to all parts of the application is not a good idea.
And we need to restrict the use from accessing certain routes until the user
performs a specific action like login to the application. So, you can use route
guards for the following scenarios.
a. Restrict a user from accessing a route.
b. Ask the user to save changes before moving away from view.
c. Validating the route parameters before navigating to the route.
d. Fetch some data before you display the component view of a route.

Type of Route Guard


1. CanActivate
Angular

a. This guard decides if a route can be accessed by a user or not. This guard
is useful in the circumstances where the user is not authorized to navigate
to the target component.
2. CanActivateChild
a. This guard decides if a user can leave a route or not. This guard is useful
in cases where the user might have some pending changes, which was
not saved.
3. CanDeactivate
a. This guard determines whether a child route can be activated or not.
4. Resolve
a. This guard delays the activation of the route until some tasks are
complete. You can use the guard to pre-fetch the data from the backend
API, before activating the route.
5. CanLoad
a. The CanLoad guard prevents the loading of the lazy-loaded module. We
generally use this guard when we do not want unauthorized users to be
able to even see the source code of the module.

Route Guard Implementation


1. Angular 14 & Lower Versions
a. Create a service that inherits from a specific route guard interface.
b. Implement the method provided by that route guard interface.
c. Return a boolean value/data from that method.
d. Assign the service to route guard property of the route object.
2. Angular 15 & Higher Versions
a. Create a function that should return a boolean value/data.
b. Assign that function to a specific route guard property of the route object.

CanActivate Route Guard


1. The Angular CanActivate route guard decides if a route can be activated or not.
We use this route guard when we want to check on some condition, before
showing the component view to the user.

CanActivate Route Guard Use Case


1. The common use case where we can use a CanActivate Route guard is when we
want to protect a route from an unauthorized user. For example, let’s say some
routes can only be accessed by a logged-in user, we can use CanActivate guard.
Angular

CanActivate Guard: Angular 14 & Lower versions


1. Create a service that inherits from the CanActivate interface.
2. Implement the CanActivate method provided by the CanActivate interface.
3. Return a boolean value from the CanActivate method based on whether the
route can be activated or not.
4. Assign the service to the canActivate property of the route object.

CanActivateChild Route Guard


1. The Angular CanActivateChild Route Guard runs before we navigate to a child
route guard. This guard is very similar to the CanActivate route guard and it
protects a child route from unauthorized access.

CanDeactivate Route Guard


1. We use the CanDeactivate route guard to decide if the user can navigate away
from a route or not. This route guard is called whenever we try to navigate away
from the current route.

CanDeactivate Route Guard Use Case


1. The best use case where we can use the CanDeactivate route guard is when the
user has filled a form like a registration form and tries to navigate away without
submitting it. In that case, before navigating the user away, we might want to
confirm if he wants to submit the data.

Resolve Route Guard


1. Resolve route guard in Angular can be used when we want to load some data
before we navigate to a route.

What are Navigation Events


1. In Angular, when we navigate from one route to another route, there is a
sequence of navigation events that get triggered by the Angular router. We can
subscribe to these events and execute some logic if we want…

What is a pipe?
1. Pipes in Angular are used to transform or format data before displaying it in the
view. Angular pipe takes data as an input and it formats or transforms that data
before displaying it in the template.
Angular

How to create a custom pipe?


1. We can create a custom angular pipe in three simple steps:
a. Create a typescript class and export it. By convention, a pipe class name
should end with Pipe.
b. Decorate that class with @Pipe Decorator. There we can specify a name
for the pipe.
c. Inherit the PipeTransform interface and implement its transform method.

Why do not use pipes for filtering or sorting?


1. The angular team always recommends not to use pipe to filter or sort data. When
we use pipe for filtering or sorting data, it can significantly impact the
performance of the application, if not implemented carefully.

What is a pure pipe?


1. A pure pipe is a pipe that gets called whenever there is a pure change in the
input value. By default, every pipe is a pure pipe.

What is pure change?


1. The following changes are considered pure changes in data:
a. If the pipe is being used on a primitive type like string, number, boolean,
etc. And if the value of that primitive type changes, it is considered a pure
change.
b. If the pipe is being used on a reference type input, and if the reference of
that input changes, then the change is pure change.
c. NOTE: But if the input is of reference type, and only its property value
changes and its reference has not changed, that change is not a pure
change.

What is an impure pipe?


1. A pipe is an impure pipe if it is not pure. An Impure pipe gets called for each
change detection cycle and it is performance intensive.

Async pipe
1. The async pipe allows us to handle asynchronous data. It allows us to subscribe
to an observable or promise from the view template and returns the value
emitted.
Angular

What is a Dynamic Component


1. Dynamic components are those components that we create dynamically at
runtime.
2. The dynamic component is not a specific feature provided by Angular. Instead, it
is just like a normal component, which gets created on runtime. We create or
render dynamic components by writing some code.

How to render Dynamic Component


1. Using ngIf Directive
a. <app-delete *ngIf=”show”><app-delete>
b. We use the *ngIf directive on the component which we want to render
dynamically. To *ngIf directive, we assign a typescript expression which
should return a Boolean value.
2. Using Dynamic Component Loader
a. LoadComponent(data) { //Write logic to load component }
b. Using this approach, we can create and render a component by writing
some code, and then we can manually attach it to the DOM.

Template Driven Form


Why not use the normal HTML Form?
1. When a Normal HTML form is submitted, it reloads the page by making an HTTP
request to the server. Since we create a single-page application using Angular,
we can say that it will restart the complete Angular application.
2. To avoid this, we need Angular’s help to stop this default behavior. This can be
achieved using a template-driven form or reactive form in Angular. Using any one
of these two approaches makes working with forms easier.

What is template-driven form?


Template Driven Form
1. Advantage:
a. Less coding is required in the component class.
b. Easy to understand and start with.
2. Disadvantage:
a. Difficult to add controls dynamically at runtime.
b. Unit testing is challenging with TD forms.
Reactive Form
Angular

1. Advantage:
a. The structure of the form is defined in the TypeScript class.
b. Creating dynamic controls is easier.
c. Easy to unit test.
2. Disadvantage:
a. Most of the things are done by writing code.

TD Required Module?
1. To work with forms in Angular, we must import FormsModule from
@angular/forms in the App Module file.

Touched & Untouched Property?


1. A form is considered as touched if any of its control has been focused. For a
touched form its touched property will be true and its untouched property will be
false.
2. A form of control is considered as touched if that form of control has been
focused. For a touched form control its untouched property will be false.

Dirty Property?
1. A form is considered as dirty if any of its control values have changed. For a dirty
form, its dirty property will be true.
2. A form control is considered as dirty if that form control value has changed. For a
dirty form control its dirty property will be true otherwise false.

What is a Form group?


1. A FormGroup is a collection of FormControl. It can also contain other
FormGroup.
2. To create a form group, we can use the ngModelGroup directive.
3. We create a FormGroup to organize and manage Form Controls together. We
can track the value and validity state of form control instances present inside a
FormGroup.

The setValue() method


1. The setValue() method is used to update a FormControl, FormGroup, or
FormArray value.
2. To the setValue() method, we pass an object to update the value of a
FormControl, FormGroup, or FormArray. The structure of that object must match
Angular

the structure of FormControl, GormGroup, or GormArray which we are trying to


update.

The patchValue() method


1. The patchValue() method is used to update only a subset of the element of
FormGroup or FormArray value.
2. It will only update the matching objects and ignore the rest.

Reactive Forms
Required Module?
1. To work with forms in Angular, we must import ReactiveFormsModule from
@angular/forms in the App module file.

What is a FormArray?
1. A FormArray is a way to manage a collection of form controls in Angular. The
form control can be a FormGroup, FormControl, or another FormArray.
2. In Angular, we can group form controls in two ways.
a. Using FormGroup
b. Using FormArray
3. The difference between FormGroup and FormArray is in the way they create
the collection.
a. FormGroup stores the form controls in the form of a key-value pair in an
object.
b. FormArray stores the form control as an element of an array.

Async Validator?
1. We use an async validator when we need to send an HTTP request to the server
to check if the data entered in a form element is valid or not.
a. The async validator must return either a promise or an observable.
b. Angular does not provide any built-in async validator.

The ValueChanges() Event


1. The ValueChanges is an event that is raised by Angular forms whenever the
value of the FormControl, FormGroup, or FormArray changes.
Angular

The statusChanges Event


1. The statusChanges is an event that is raised by Angular forms whenever
Angular calculates the validation status of a FormControl, FormGroup, or
FormArray changes.

The setValue() method


1. The setValue() method is used to update a FormControl, FormGroup, or
FormArray value.
2. To the setValue() method, we pass an object to update the value of a
FormControl, FormGroup, or FormArray. The structure of that object must match
the structure of FormControl, FormGroup of FormArray which we are trying to
update.

The patchValue() method


1. The patchValue() method is used to update only a subset of the element of
FormGroup, or FormArray value.
2. It will only update the matching objects and ignore the rest.

HTTP Request Core Parts


URL
1. The most important part of an HTTP request is the URL to which we are sending
the request. If we are making an HTTP request to an API, in that case, that URL
is also called as API endpoint.
2. For example, an API URL looks something like below:
a. yourdomain.com/api/products/id

HTTP Verbs
1. When communicating with the RESTful APIs, it's not just the URL that matters,
but also the HTTP verbs you are using.

HTTP Request headers


1. When making an HTTP request to the server, along with API endpoint and HTTP
verbs, we also need to send some additional metadata to the server with the
request we are sending.
Angular

2. HTTP Request headers are optional and the client sets some default headers for
an HTTP request.
3. However, it is also possible to set HTTP request headers of your own when
sending the request to the server.

Request body
1. For some of the HTTP verbs, we also need to specify the body i.e., the data
which we want to send with the request.
2. Not all the request needs to have a body. HTTP requests like POST, PUT,
PATCH, etc. need to have a body. And requests like GET need not have a body.

Interceptor
What is an Interceptor?
1. The Angular interceptor helps us to modify the HTTP Request by interacting with
it before the Request is sent to the server. It can also modify the incoming
Response from the server.
2. The interceptor globally catches every outgoing and incoming request at a single
place.
3. We can use it to add custom headers to the outgoing request, log the incoming
response, etc.

Module
What is a Module?
1. A module in Angular is a way of bundling the Angular building blocks like
components, directives, services, pipes, etc. together. A module gets scanned by
Angular to be aware of what features are being used in that Angular project.
a. To make a class as a module class, we need to decorate it with NgModule
decorator.
b. Every Angular application must have at least one module file. (not in the
case of standalone components.)

SUMMARY
1. Angular analyses the NgModule directive of a class to understand what building
blocks you need in your angular application.
Angular

2. Every Angular application requires at least one main module. But we can split the
main module into multiple modules.
3. We also declare Angular’s code modules which we want to use in our Angular
application, inside the module class.
4. You cannot use Angular building blocks like components, directives, services,
pipes, etc. without declaring them in the module file.

What is a Feature Module?


1. We can split the main module into smaller feature modules. A feature module
contains all the building blocks like components, directives, etc. Of a given
feature of an Angular application.
2. NOTE: Every module is standalone and they work independently from each
other. One module does not have access to imports or exports of other modules.

What is a Shared Module?


1. A shared module contains all the components, directives, and pipes which can
be shared between different modules. We only need to import the shared module
once in other modules, and all the esports from the shared module will be
available in that module.
2. NOTE: A component, directive, module, or pipe can be declared only once in an
Angular application.

What is a Core Module?


1. The purpose of the core module is to provide a central place for defining
services, single instance components, configuration settings, utils, helper classes
& functions, and any other code that is used across the entire application.
2. NOTE: The core module is typically imported only once, in the main module i.e.
AppModule.

Feature Module: Points to Remember


1. In a feature module, we declare all the related components, directives, pipes, etc.
which we want to use for that feature.
2. When we declare components, directives, and modules in a feature module, if
those components, directives, pipes, etc. are not being used outside of that
module, we don’t need to export it.
3. When we define a separate route for a feature module, the components which
we are using in that route, must be declared in the feature module.
Angular

Eager Loading
1. In Eager loading, all modules listed in the imports array of the AppModule are
loaded synchronously, during application startup.
2. Eager loading is the default behavior in Angular.
3. This means that all components, directives, services, and pipes defined within
those modules are available immediately.
4. Everything is loaded at once when the angular application runs.
5. Benefits:
a. Simple to implement, especially for smaller applications.
b. Components from any module are readily available for use throughout the
application.
6. Drawbacks:
a. Larger initial bundle size as all modules are loaded upfront.
b. This can lead to slower initial load times for complex applications.

Lazy Loading
1. Lazy loading allows you to load modules asynchronously, only when the user navigates
to a route associated with that module.
2. When the angular application starts for the first time, it only loads the main AppModule.
Other modules are not loaded at the application start.
3. Once the user navigates to another route, only then the module related to that route will
be loaded.
4. This optimizes the initial load time by deferring the loading of less frequently used
features.
5. Benefits:
a. Smaller initial bundle size, leading to faster initial load times.
b. Improves perceived performance by loading features only when needed.
6. Drawbacks:
a. Requires additional configuration for routes and lazy loading.
b. There might be a slight delay when a lazy-loaded module is first accessed.

Signal
What is signal?
1. A signal is a wrapper around a value that can notify interested consumers when
that value changes. Signals can contain any value, from simple primitives to
complex data structures.
Angular

Introduction to Signals
1. Currently, the signal feature is just a developer preview. This feature is likely to
be stable once Angular version 17 is released.
2. Without signals, Angular application relies on a change detection cycle to find out
if some data has changed, and then update the UI based on that change.
3. Signals give us an alternative way of managing and detecting changes in the
data and updating the UI. In this way, it allows Angular to get rid of that extra
zone.js library.
4. With signals, we do not have automatic change detection at all. Instead, we as a
developer tell Angular when the data changes.
5. In this way, signals lead to better performance and a smaller bundle.

Disadvantage of Change Detection


1. A change detection cycle runs very frequently even when something has not
changed in the Angular app. This can impact the performance of Angular
applications.
2. Behind the scenes, the change detection cycle algorithm uses a library called as
zone.js. This overall increases the bundle size of the Angular application.
3. The zone.js library also does not tell angular which component has changed and
what part. Because of this, every time the change detection cycle runs, the whole
component tree gets re-rendered.

How to update Signal Value


1. To update the value of a signal, we need to call a method on the signal object.
For that, Angular provides us with three methods.
a. Set()
b. Update()
c. Mutate()

Difference between update() & mutate()


1. The mutate() method works just like the update method. The only difference is
that you can use mutate() method only on mutable values.
2. The update() method overrides the existing value and creates a new value. It
does not change the existing value.

The computed() & effect() Function


1. computed()
Angular

a. We use the computed() function to compute a value from a signal value.


2. effect()
a. We use the effect() function whenever we want to execute some code
when the value of a signal changes.

Conclusion
1. Signals are the new feature introduced in Angular 16. It gives developers control
to tell Angular when it should update the UI when data changes.
2. This feature is not final & stable yet and it is currently in developer preview. And
there are more features to be added to signals.

Standalone Components
What are Standalone Components?
1. A standalone component is a special type of component that does not require to
be declared in the NgModule of a module class. It simplifies the development
process by eliminating the need for NgModule.
a. No NgModules: Standalone components don’t need to be declared in any
NgModule.
b. Simpler development: They streamline the development experience by
reducing boilerplate code.
c. Can be used with NgModules: Standalone components can still be used
alongside components within NgModules.

You might also like