Angular
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.
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.
Advantage of Typescript
1. Typescript is a superset of javascript.
2. Typescript has additional features feature
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.
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
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
@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:
Dependency injection:
1. A dependency is a relationship between two software components where one
component relies on the other component to work properly.
Angular
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.
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
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.
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
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 (“../”) 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’);
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
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.
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
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
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.
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.
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.
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.
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.
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.
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.