Unit-5 Angular

Download as pdf or txt
Download as pdf or txt
You are on page 1of 63

UNIT-5

WHAT IS ANGULAR?
• Angular is a popular open – source web application framework created and maintained
by Google.
• It is used for building dynamic, single – page applications (SPAs) that run in a web
browser.
• Angular is built on the principles of declarative programming, dependency injection,
and reactive programming, and it offers a wide range of features and tools that make it
a powerful tool web developer.
• Angular uses HTML, CSS, and JavaScript to build the user interface of an application,
and it provides a range of built – in tools for routing, data binding, forms management,
and more.
• One of the key benefits of using Angular is that it provides a structured and organized
approach to building web applications, which can help improve code maintainability
and scalability.
• It also offers a robust ecosystem of tools, libraries, and documentation, which makes it
easier for developers to learn and use.

FEATURES OF ANGULAR

Here are some of the key features of Angular.

• Two – way data binding: Angular offers two – way data binding, which means any
changes made to the user interface will be reflected in the data model and vice versa.
• Component – based architecture: Angular applications are built using reusable
components, making it easier to manage and scale large applications.
• Directives: Angular provides built – in directives that allow you to extend HTML with
new attributes and tags, making it easier to create dynamic views.
• Templates: Angular templates allow you to define the user interface of your application
using HTML, making it easy to create and modify views.
• Testing: Angular provides robust testing capabilities, making it easier to write and run
tests for your application.
• paltforms, including web, mobile, and desktop.
• TypeScript: Angular is built using TypeScript, a superset of JavaScript that adds static
typing and other features to the language, making it easier to write and maintain large
applications.
• Large community: Angular has a large and active community of developers, making
it easy to find support, resources, and plugins for your application.

ANGULAR APPLICATION SETUP

To set up an Angular application, you will need to follow these steps:

• Install Node.js: Angular requires Node.js. You can download and install from the
official Node.js website.
• Install Angular CLI: Angular CLI is a command – line interface tool that makes it
easier to create and manage Angular projects. You can install it globally using the
following command. npm install -g @angular/cli

• Create a new project:To create a new Angular project, use the Angular CLI command
ng new project-name. This will create a new project with the default configuration.
You can use command prompt or editors like visual studio code to create, run and
maintain the angular projects.
Let’s assume our project name is Demo
• Serve the application: Once the project is created, navigate to the project directory using
the command cd project-name to open the project.

• These are the basic steps for setting up an Angular application. Once you have the
application set up, you can start developing it further adding components, services, and
other features of Angular framework.

COMPONENTS

• Components are building blocks of an application that are responsible for controlling a
part of the user interface. They are reusable and modular, making it easy to develop and
maintain large applications.
• Components consists of HTML, CSS and JavaScript code attached to it and a separate
testing file.
• For every angular application there must be atleast one component.

Creating a component

In terminal use the following command to create a component ng generate component


component_name or ng g c component_name.

Whenever we create a component four files will be created by default they are
‘app.component.html’ , ‘app.component.css’ , ‘app,component.spec.ts’ , ‘app.compnent.ts’

app.component.html:

• It is the template file for the root component of an Angular application. This file defines
the structure and layout of the component, and specifies how its data should be
displayed.
• The HTML file includes standard HTML tags as well as Angular – specific directives,
which allow you to bind data to the view and create dynamic, interactive components.
• When you create a new Angular application using CLI command ng new, the
app.component.html file automatically generated for you, along with other files that
make up the initial Angular project structure. You can customize the contents of this file
to suit the needs of your application.
app.component.css:

• It is a Cascading Style Sheets (CSS) file that is used to define the styled and layout for
the root component of an Angular application. It is a separate file from the template file
app.component.css to keep the concerns of styling and layout separate from the HTML
structure and logic
• This file will also automatically created when you create a new angular application.

app.component.spec.ts:

• It is a file that contains the unit tests for the AppComponent class in an Angular
application. It is automatically generated when you create a new Angular application
using the CLI command ng new.
• In Angular, unit testing is an important part of the development process, as it helps to
ensure that the application works correctly and reliably. The app.component,spec.ts file
contains a series of tests that verify the behaviour of the AppComponent class under
different conditions.
• The tests in app.component,spec,ts are written using Jasmine testing framework, which
is included with Angular. The tests are executed using the Karma test runner, which is
also included with Angular
• The app.component.spec.ts file typicslly contains a number of test cases, each of which
verifies a specific aspect of the AppComponent class.

app.component.ts:

• app.component.ts is a file that defines the main component of an Angular application.It


is automatically generated when you create a new Angular application using the CLI
command ng new.
• The app.component.ts file also typically includes a template that defines the HTML
markup for the component. The template can include placeholders for dynamic content,
which are filled in at runtime based on the state of the component.
• The AppComponent class in app.component.ts can also include other components as
child components, which allows you to create a hierarchical structure of components
that work together to define the overall behaviour of the application.

we can include one component to another using the components selector. We can find selector
in app.component.ts file.
SELECTOR:

In Angular, a selector is used to identify the component or directive on the HTML page. It is a
string used to match the HTML elements with the corresponding component’s template. A
selector can ne used to define a custom HTML tag for a component or can also be used to match
an existing HTML element on the page. The selector is defined in the component’s metadata
using the @Component decorator.

Decorator: Decorator is a special kind of declaration that can be attached to a class declaration,
method, accessor, property, or parameter. Decorators are used to modify the behaviour of these
declarations at runtime without actually modifying the original source code.

In Angular, decorators are extensively used to provide metadata for the components, directives,
and services. For example, the @Component decorator is used to provide metadata for a
component, including the selector, template, and styles.

Selector name will be default also we can change selector name as we like. We have to include
the selector name as a tag i.e., <app-root></app-root> in the another components
app.component.html.
index.html is the only file which will be executed when we run the application. We can include
selectors here as a html tag. One index.html file can take only one selector name as tag.

MODULES

• In Angular, a module is a container for organizing related components, directives,


services, and pipes of application. It is a way of organizing an application into smaller,
functional and reusable pieces.
• Whenever we create an application automatically a module will be created.
• It is a normal typescript file unless it contains @NgModule decorator. We have to pass
an object to this decorator. In that objects there will be different keys like declarations,
imports, exports, providers and bootstarp.
• These properties allow you to specify which components, directives, pipes, and services
belong to the module, what other modules are needed to access their functionality,which
components, directives, and pipes should be available for use outside of the module,
which services should be available at the application level, and which component
should be bootstrapped when the module is loaded.

The @NgModule decorator has the following properties:

• declarations: This property is used to define the components, directives, and pipes
that belong to the module.
• imports: This property is used to export the components, directives, and pipes of the
module so that they can be used in other modules.
• providers: This property is used to provide services that are available throughout
the module.
• bootstrap: This property is used to define the component that should be
bootstrapped when the module is loaded.

By using the @NgModule decorator, developers can organize their application into separate
modules, each with its own set of components, directives, pipes, and services. This makes the
application easier to maintain and test.
Creating a new component:

We can create a module using the following command ng g m module_name. For example, if
we have to create a module called test then ng g m test. The module file contains test.module.ts
as its module name.

EXECUTING AN ANGULAR APPLICATION

• Executing an Angular application is a broader term that can refer to any number of
actions that involve running or manipulating an Angular application.
• When you execute an application, it involves multiple steps, such as compiling the
code, linking the libraries, and then running it. Running an application refers to the final
step in the execution process, where the compiled and linked application is executed,
and the output is produced.
• To run the application we have to use ng serve command. When we run this command
we will get a port address http://localhost:4200. We have to search this address in
browser to see the output.
• Localhost:4200 is the default port used by Angular to run the development server. When
you run the ng serve command, Angular starts a development server and serves your
application on this port.
• If you have multiple Angualr applications running on your machine, each application
will have a different port number assigned to it. So, if you have another Angular
application running on port 4200, you may need to use a different port number for your
new application.

ELEMENTS OF TEMPLATE

• In Angular, a template is an HTML file that contains the view of the application. It
defines how the application data should be rendered on the screen. A template can
contain Angular-specific syntax and directives that help in manipulating the data and
controlling the rendering of the view.

• When the application runs, Angular takes the template and combines it with the
component to create a view. This view is then rendered on the screen for the user to
see.
• The elements of an Angular template include HTML tags, Angular directives, and data
bindings. HTML tags define the structure and layout of the view, Angular directives
provide additional functionality to the view, and data bindings connect the view with
the component data.

In Angular, a template is a blueprint or a skeleton structure of the user interface that defines
how the application will be rendered in the browser. The elements of a template in Angular
include:

1. Interpolation: Interpolation is used to display dynamic data in the template by using


curly braces({{ }}). It binds the data from the component to the HTML template.
2. Directives: Directives are used to add extra behavior or attributes to HTML elements.
There are two types of directives in Angular- Structural and Attribute directives.
3. Pipes: Pipes are used to transform the data in the template. For example, the date pipe
is used to format the date and the uppercase pipe is used to convert the text to uppercase.
4. Event binding: Event binding is used to handle user events like button clicks, keypress,
and mouse events. It binds the events from the template to the component.
5. Property binding: Property binding is used to set the properties of the HTML elements
in the template. It binds the data from the component to the HTML template.
6. Two-way binding: Two-way binding is used to bind the data in both directions. It allows
the user to change the data in the component and the component to change the data in
the template.
7. Template reference variables: Template reference variables are used to reference an
HTML element from the template in the component.

These are the main elements of a template in Angular.

CHANGE DETECTION
• In Angular, change detection is the process of detecting changes to the data associated
with a component or directive and updating the view accordingly. When data changes,
Angular automatically updates the view to reflect the changes.
• Angular uses a unidirectional data flow, which means data flows in one direction from
the component to the view. When a component’s data changes, Angular’s change
detection system detects the changes and updates the view.

• There are two strategies for change detection in Angular: default and OnPush.

DEFAULT

• In the default strategy, Angular checks for changes to component properties and their
children.

• Whenever there is a change in the state of the application, the change detection
mechanism triggers a change detection cycle. This cycle starts from the root component
and works its way down the component tree, checking for changes in each component.

• In the default change detection strategy, Angular uses the dirty checking mechanism to
detect changes. It compares the previous and current values of a property to detect
changes. If there is a change, it updates the view.

• However, this strategy can be inefficient when dealing with large datasets, as it can lead
to a lot of unnecessary checks. In such cases, it is recommended to use other change
detection strategies such as "OnPush" change detection.

• Overall, the default change detection strategy in Angular provides a convenient way to
detect changes and update the view accordingly.

ONPUSH

• In the OnPush strategy, Angular only checks for changes when the input properties to
the component have changed, or if an event has been triggered within the component.

• The "OnPush" change detection strategy is a performance optimization technique that


reduces the number of change detection cycles and improves the performance of an
Angular application. When using the "OnPush" strategy, Angular only checks for
changes when the component's inputs change or an event occurs that triggers a change
detection cycle.
• To use the "OnPush" change detection strategy, you need to set the changeDetection
property of the component to ChangeDetectionStrategy.OnPush. This tells Angular
to use the "OnPush" strategy for the component.

• When using the "OnPush" strategy, you also need to be aware of how you handle the
component's inputs and state. The component's inputs should be immutable, meaning
they should not change reference unless their value actually changes. If a change occurs
to the input object, but the object reference remains the same, the "OnPush" strategy
won't detect the change and won't trigger a change detection cycle.

• Additionally, any changes to the component's state or properties should be made using
immutable techniques, such as creating a new object reference instead of updating the
existing object.

• Overall, the "OnPush" change detection strategy can help improve the performance of
an Angular application by reducing the number of change detection cycles, but it
requires careful handling of the component's inputs and state to work effectively.

Change detection is a key concept in Angular, as it allows for the creation of dynamic,
responsive user interfaces that can react to changes in data in real time.

STURUCTURAL DIRECTIVES

AngularJS is an open-source JavaScript framework that is used for building dynamic web
applications. Structural directives in AngularJS are a way to manipulate the DOM structure
based on some condition.

Structural directives are used to add, remove, or manipulate elements in the DOM based on
certain conditions. There are three main structural directives in AngularJS:

1.ngIf: The ngIf directive is used to add or remove an element from the DOM based on a
condition. If the condition is true, the element is ngFor: The ngFor directive is used to repeat a
set of elements based on added to the DOM. If the condition is false, the element is removed
from the DOM.

2.ngfor:a collection. It is typically used to create a list of items from an array or an object.
3.ngSwitch: The ngSwitch directive is used to conditionally render content based on a given
expression. It evaluates an expression and then displays a particular template based on the result
of the evaluation.

To use these directives, you need to include the "ng" prefix in the HTML element, followed by
the name of the directive. For example, to use the ngIf directive, you would use it as

Similarly, you can use the ngFor and ngSwitch directives as follows:

Overall, structural directives in AngularJS provide a powerful way to manipulate the DOM
based on various conditions, and they can be extremely useful in creating dynamic web
applications.
Ng -IF:
In AngularJS, you can use the ng-if directive to conditionally render elements in the DOM
based on an expression. Here's an example:
In this example, the <div> element is only rendered in the DOM if the expression showElement
evaluates to a truthy value. If showElement is falsy, the element is not rendered.

You can also use the ng-if directive with an else clause, like this:

In this example, if showElement is truthy, the first <div> element is rendered, and if it's falsy,
the second <div> element is rendered.

Ng-for:

ngFor is an Angular directive used to render a list of items. It's typically used in
combination with an array or iterable object to create a list of items in the DOM.

Here's an example of how ngFor can be used in an Angular component template:

In this example, ngFor is used to loop through the items array and create a <li> element for
each item. The let keyword is used to create a local variable item that represents the current
item in the loop.

ngFor also allows you to access the index of each item in the loop:
In this example, the index variable is used to access the current index of the loop.

ngFor can also be used with objects:

In this example, ngFor is used to loop through an array of objects (people) and create a <li>
element for each object. The local variable person represents the current object in the loop, and
its properties (name and age) are used to display data in the template.

Ng-switch:

ng-switch is a directive in AngularJS that conditionally displays a portion of HTML


code based on the value of an expression.

The syntax of ng-switch is as follows:

The ng-switch directive evaluates the expression and then checks each ng-switch-when
directive for a match. If a match is found, the content of the corresponding element is displayed.
If no match is found, the ng-switch-default element is displayed (if it is present).

Here's a breakdown of the syntax:


•ng-switch is the directive that specifies the expression to be evaluated.

•ng-switch-when is a child directive that specifies a value to be matched against the expression.

•ng-switch-default is a child directive that specifies the default content to be displayed if no


matches are found.

Here's an example of ng-switch in action:

In this example, the ng-switch directive is evaluating the color expression. If the value of color
is "red", the first ng-switch-when element is displayed. If the value of color is "green", the
second ng-switch-when element is displayed. If the value of color is "blue", the third ng-switch-
when element is displayed. If the value of color is anything else, the ng-switch-default element
is displayed.

CUSTOME STRUCTURAL DIRECTIVES

AngularJS has a powerful feature called directives that allows you to create custom HTML tags
and attributes with custom behavior. There are three types of directives in AngularJS:
components, attribute directives, and structural directives. In this response, I'll focus on
creating custom structural directives.

A structural directive is used to change the structure of the HTML DOM by adding, removing,
or manipulating elements. Examples of structural directives in AngularJS include ngIf, ngFor,
and ngSwitch.

To create a custom structural directive, you can use the $compile service to dynamically add
or remove elements from the DOM based on a condition. Here's an example:
In this example, we've defined a custom directive called myDirective. We're using the restrict
option to restrict the directive to an attribute (A). In the link function, we're using the element
parameter to get a reference to the element on which the directive is applied. We're then using
the $compile service to dynamically create HTML based on a condition, and then adding it to
the DOM using the after method.

To use this directive in your HTML, you would add the my-directive attribute to an element,
like:

When the condition in the directive's link function evaluates to true, the HTML inside the if
statement will be added to the DOM after the div element.

ATTRIBUTE DIRECTIVES:

In AngularJS, attribute directives are a type of directive that allow you to attach behavior to
elements in the DOM (Document Object Model) by decorating them with a specific attribute.
Attribute directives are denoted by an attribute name that begins with ng- or data-ng-.

Attribute directives can modify the behavior, appearance or structure of the element they are
attached to. They can also add or remove DOM elements and manipulate the data in the scope
of the element.
To create an attribute directive in AngularJS, you need to define a directive function using the
directive() method of the AngularJS module. The directive function takes a configuration object
as a parameter, which specifies the behavior of the directive.

Here is an example of a simple attribute directive that changes the background color of an
element to yellow when the user hovers over it:

In the above example, the restrict property is set to 'A', which means the directive will be
applied as an attribute. The link function is used to define the behavior of the directive. In this
case, it adds event listeners to the element to change the background color on mouseenter and
mouseleave events.

To use the directive in HTML, simply add the attribute to the element:

When the user hovers over the element, the directive's behavior will be applied and the
background color will change to yellow.
Ng-style:

ngStyle is an attribute directive in Angular that allows you to dynamically set CSS
styles on an element based on data in the component.

You can use ngStyle in the template of an Angular component by binding it to a property or
expression that returns an object. The keys of this object represent the style properties you want
to set, and the values represent the corresponding values for those properties.

Here's an example of how you can use ngStyle in your Angular template:

In this example, we're using ngStyle to dynamically set the font-size and color styles of the div
element based on the object we pass to it. You can also bind to a method that returns an object,
allowing you to dynamically generate the styles based on the component's data.

In this example, getTextStyle() is a method that returns an object representing the desired styles
for the div element based on the component's data. This allows you to dynamically generate
styles based on the component's state.

ngStyle is a powerful directive that allows you to create dynamic, data-driven styles in your
Angular templates.

Ng-class:

In Angular, attribute directives are a type of directive that can be used to modify the
behavior or appearance of HTML elements. One example of an attribute directive in Angular
is the ngClass directive.
The ngClass directive allows you to dynamically set CSS classes on an HTML element based
on conditions in your component. For example, you might use the ngClass directive to apply a
certain CSS class to an element when a certain variable in your component is true.

Here's an example of how you might use the ngClass directive in your Angular template:

In this example, the ngClass directive is bound to an object with two properties: my-class and
other-class. Depending on the value of the myVariable variable in your component, one of these
classes will be applied to the div element.

You can also use the ngClass directive to conditionally apply multiple classes based on different
conditions. For example:

In this example, an array of classes is passed to the ngClass directive. The first class, class-1,
is always applied to the element. The second class, either class-2 or class-3, is applied based
on the value of myVariable. The third class, class-4, is only applied if anotherVariable is true.

CUSTOM ATTRIBUTE DIRECTIVE


In Angular, a custom attribute directive is a feature that allows you to define your own behavior
for HTML elements using attributes. It allows you to extend the functionality of HTML
elements by attaching custom behavior or styles to them.
To create a custom attribute directive in Angular, you need to follow these steps:
Step 1: Create a new directive Create a new directive using the @Directive decorator provided
by Angular. You can do this by defining a class with the @Directive decorator and specifying
the selector for your directive. The selector is the attribute name that you want to use in your
HTML to apply the directive.
For example, the following code creates a custom attribute directive called
MyCustomDirective with a selector of myCustomDirective:
Typescript code:
import { Directive, ElementRef } from '@angular/core';
@Directive({ selector: '[myCustomDirective]'
})
export class MyCustomDirective {
constructor(private el: ElementRef) {
// Directive logic here } }
Step 2: Define the directive's behavior Inside the directive class, you can define the behavior
that you want to apply to the elements with the directive applied. You can use the ElementRef
class, which is injected in the constructor, to get a reference to the DOM element that the
directive is applied to.
For example, you can modify the element's style, add event listeners, or manipulate the DOM
in any other way:
Typescript code:
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[myCustomDirective]'
})
export class MyCustomDirective {
constructor(private el: ElementRef) {
// Directive logic here
el.nativeElement.style.backgroundColor = 'yellow';
}
}
Step 3: Use the directive in your HTML You can now use your custom attribute directive in
your HTML by adding the myCustomDirective attribute to an HTML element:
HTML CODE:
<div myCustomDirective>
<!- -content here>
</div>
PROPERTY BINDING
Property binding refers to the process of associating a value or expression with a property of
an object or element in computer programming and user interface design. It allows the value
of a property to be automatically updated based on changes to the bound value or expression.

In the context of web development, property binding is commonly used in frameworks and
libraries like Angular, React, and Vue, where it enables dynamic data binding and facilitates
the synchronization of data between different parts of a user interface.

Property binding typically involves a source property, which is the value or expression that is
being bound, and a target property, which is the property of the object or element that is being
updated based on the changes in the source property. When the source property changes, the
target property is automatically updated to reflect the new value.

For example, in Angular, property binding is denoted by square brackets []. Let's say you have
a component with a property message and you want to bind its value to the innerText property
of an HTML element. You can use property binding like this:

Property binding is a powerful feature that enables developers to create dynamic and interactive
user interfaces by establishing relationships between data and UI elements, allowing for real-
time updates and synchronization of data across different parts of an application.
Type script code:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
}
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'] })
export class AppComponent
name="bruce" }
HTML code:
<h1>property binding in angular</h1>
o/p: property binding in angular
bruce
ATTRIBUTE BINDING
Attribute binding is a technique used in web development to dynamically update the attributes
of HTML elements based on values or expressions in a programming language, typically in the
context of a web framework or library. Attribute binding allows developers to set or modify
attributes of HTML elements based on changing data or conditions, making web applications
more dynamic and interactive.

In many web frameworks and libraries, attribute binding is denoted by square brackets [],
similar to property binding. However, there are differences in how attributes and properties are
updated in HTML elements.

Attributes are the settings or properties that define the characteristics of an HTML element and
are specified in the HTML markup using the element's attributes. For example, the src, href,
class, and id attributes are common attributes used in HTML elements. Attributes are typically
used to define the initial state or static properties of an element.

Attribute binding allows you to dynamically set or modify the value of an attribute using data
or expressions from your programming language. For example, in Angular, you can use
attribute binding to dynamically set the src attribute of an <img> element as follows:
HTML code
<!- - HTML template - ->
<img [src]= “imageURL”>

Type script code


// Angular component
export class MyComponent {
imageUrl = 'example.com/image.jpg';
}

In the above example, the src attribute of the <img> element is bound to the imageUrl property
of the Angular component. If the imageUrl property changes in the component, the src attribute
of the <img> element will be automatically updated to reflect the new value, resulting in the
loading of a new image.

Attribute binding is useful for dynamically setting attributes based on changing data or
conditions, allowing for more interactive and responsive web applications. However, it's
important to note that not all HTML attributes can be bound using attribute binding, as some
attributes are read-only or reserved for specific purposes. In such cases, property binding or
other techniques may be more appropriate.

STYLE AND EVENT BINDING


Style binding and event binding are two common techniques used in web development to
dynamically apply styles and handle events in HTML elements. They are often used in
conjunction with frameworks or libraries to create dynamic and interactive user interfaces.

Style Binding: Style binding allows you to dynamically apply styles to HTML elements based
on values or expressions from your programming language. It is denoted by square brackets []
followed by the style attribute and the style property you want to bind. The value of the style
property can be a string, a variable, or an expression. For example, in Angular, you can use
style binding to set the color and font-size properties of a <div> element as follows:

<!- - HTML template- ->


<div [style.color]= “textColor” [style.font-size.px]= “fontSize”>Hello,world!</div>
// Angular component
export class MyComponent {
textColor = 'red';
fontSize = 18;
}

In the above example, the color property of the style of the


element is bound to the textColor property of the Angular component, and the font-size
property is bound to the fontSize property. If these properties change in the component, the
corresponding styles of the element will be automatically updated to reflect the new values.
Event Binding: Event binding allows you to handle events, such as button clicks, form
submissions, or key presses, in HTML elements by associating them with event handler
functions in your programming language. Event binding is denoted by parentheses () followed
by the event name and the event handler function you want to bind. For example, in Angular,
you can use event binding to handle a button click event as follows:

HTML code
<! - -HTML template>
<button (click)= “onButtonClick()”>Click me</button>

Typescript code
// Angular component
export class MyComponent {
onButtonClick() {
console.log('Button clicked!');
}
}
In the above example, the click event of the element is bound to the onButtonClick() method
of the Angular component. When the button is clicked, the onButtonClick() method will be
executed

Event binding allows you to add interactivity to your web applications by responding to user
actions and triggering appropriate actions in your code. It enables you to create dynamic and
responsive user interfaces that can update based on user input or other events.

BUILT IN PIPES: Built-in pipes, also known as pipes in the context of web development, are
a feature in many web frameworks and libraries that allow developers to transform data in the
HTML templates. Pipes are used to format, filter, and manipulate data before displaying it in
the UI. They are denoted by a pipe (|) followed by the name of the pipe and any optional
parameters.

Here are some examples of commonly used built-in pipes in web development:
DatePipe: This pipe is used for formatting dates. It allows you to display dates in different
formats, such as short date, long date, time, etc. Example usage:
HTMLcode
<!- - HTML template>
<p>Today is {{ currentDate | date:'shortDate' }}</p>

UpperCasePipe and LowerCasePipe: These pipes are used for converting text to uppercase or
lowercase, respectively. Example usage:
HTMLcode
<!- - HTML template>
<p>{{ 'Hello World' | uppercase }}</p>
<p>{{ 'Hello World' | lowercase }}</p>

CurrencyPipe: This pipe is used for formatting currency values. It allows you to display
currency values in different formats, such as currency symbol, currency code, and decimal
places. Example usage:
HTMLcode
<!- - HTML template>
<p>Price: {{ price | currency:'USD':'symbol':'1.2-2' }}</p>

DecimalPipe: This pipe is used for formatting decimal numbers. It allows you to display
decimal numbers with a specific number of decimal places and optional thousands separator.
Example usage:
HTMLcode
<!- - HTML template>
<p>Value: {{ value | number:'1.2-2' }}</p>

PercentPipe: This pipe is used for formatting percentage values. It allows you to display
percentage values with a specific number of decimal places and optional thousands separator.
Example usage:
HTMLcode
<!- - HTML template>
<p>Percentage: {{ percentage | percent:'1.2-2' }}</p>
AsyncPipe: This pipe is used for handling asynchronous data, such as data retrieved from an
API. It automatically subscribes to an Observable or Promise and updates the UI when the data
is available. Example usage:
HTMLcode
<!- - HTML template>
<p>Data: {{ dataFromApi | async }}</p>

These are just a few examples of the built-in pipes available in many web frameworks and
libraries. Pipes are powerful tools for transforming data in the UI and making it more
presentable and user friendly. It's important to consult the documentation of the specific web
framework or library you are using for a complete list of available pipes and their usage.

PASSING PARAMETERS TO PIPES: In Angular, you can pass parameters to pipes in the
template by providing additional arguments separated by colons (:) after the pipe name. The
passed parameters can be used by the pipe for further customization of the data transformation.
Here's an example:
HTMLcode
<!- - HTML template>
<p>{{ dateValue | date:'dd/MM/yyyy' }}</p>

In this example, the date pipe is used to format the dateValue using the 'dd/MM/yyyy' format.
The 'dd/MM/yyyy' value is a parameter passed to the date pipe, specifying the desired date
format.
You can also pass multiple parameters to a pipe, separated by colons (:). For example:

HTMLcode
<!- - HTML template>
<p>{{ priceValue | currency:'USD':'symbol':'1.2-2' }}</p>

In this example, the currency pipe is used to format the priceValue as a currency value in USD
with the currency symbol, using the '1.2-2' format for decimal places. The 'USD', 'symbol', and
'1.2-2' values are parameters passed to the currency pipe, specifying the desired currency,
currency display mode, and decimal format, respectively.
You can pass any valid expression as a parameter to a pipe, including literals, variables, and
expressions. The pipe can then use these parameters to customize the data transformation based
on the provided values. Keep in mind that the specific parameters and their usage may vary
depending on the pipe you are using, so it's important to refer to the official Angular
documentation for the specific pipe for accurate usage details.

WHAT IS A COMPONENT ?
• A component is the basic building block of an Angular application.
• It is reusable.
• It has 4(files)Html,css,ts and separate testing file are present in a component.
Nested components

The Angular framework allows us to use a component within another component and when
we do so then it is called Angular Nested Components. The outside component is called
the parent component and the inner component is called the child component.

In Component 1 and 2 the data in html file is changed with the help of selector,where specified
selector name and file name should be matched then data is modified by templete url either by
address or by writing html code there itself.
Here app.component.hml is parent component and header.component.html is child component.

@Input(), @Output() decorators and EventEmitter

@Input()decorator:

@Input() decorator is used to pass data (property binding) from parent to child component. The
component property should be annotated with @Input decorator to act as input property. It is
used in a child component or directive.

@Output() decorator:

The @Output() decorator in a child component or directive lets data flow from the child to the
parent. @Output() marks a property in a child component as a doorway through which data
can travel from the child to the parent.

EventEmitter:

This is used to emit events in components. Use in components with the @Output directive to
emit custom events synchronously

Passing data from container component(parent componet) to child component

As I mentioned before AppComponent is the parent component and you can customize
app.component.html as you wish. Here I created an instance of the child component. <hr> tag
will separate the parent and child components.
After that, using app.component.ts I send a message to the child by passing a string under the
parameter called “inputText”.

The message sent by the parent component(AppComponent) will be received by the child
component(ChildComponet).

Passing data from child component to container component

Using @Output Decorator and EventEmitter (import from @angular/core) child component will
send data to the parent component. First, we need to create a variable called “outputFromChild”

with @Output Decorator, and another variable called “outputText” is needed to store and pass
the message to the parent component in the child.component.ts.

@Output() outputFromChild : EventEmitter<string> = new EventEmitter();


outputText : string = "Hi ... message from child";

Then to show that message in our console, we need to have a button in our ChildComponent
and add it to child.component.html. To fire the click we need to have a method called
“sendDataToParent”.
<button class="btn btn-success" (click)="sendDataToParent()">Send to Parent</button>

“sendDataToParent” method will implement by emitting the “outputText” in the


ChildComponent.
sendDataToParent() {

this.outputFromChild.emit(this.outputText);

Now we need to implement a method called “receiveChildData” in the app.componet.ts to


receive the message from the ChildComponent.
receiveChildData(data){

console.log(data);

To fetch the value, app.component.html must be like below.


<app-child [inputFromParent] = "inputText" (outputFromChild) =
"receiveChildData($event)"></app-child>

Then if we click the create button in the child component, “sendDataToParent()” method will
fire and the parent component will receive data from ChildComponent and the console shows
“Hi … message from child”

DOM(Document Object Model):


The Document Object Model (DOM) is an application programming interface (API) for HTML
and XML documents. It defines the logical structure of documents and the way a document is
accessed and manipulated.

The Document Object Model (DOM) is a programming interface for web documents. It
represents the page so that programs can change the document structure, style and content.

Shadow DOM in Angular :

Angular is inspired by Web components. Therefore not surprisingly, Angular comes with a
similar construct, an Angular component. In Angular, a component consists of a TypeScript
class, aka controller, a template, and styles.

Now, here’s the thing. Angular doesn’t use the native Shadow Dom by default, but it uses
Emulated Shadow Dom.The main reason for that is that back in the day when Angular was
created; most browsers were not supporting Shadow Dom.

Shadow DOM tree starts with a shadow root,underneath which can be attached to any elements
you want, in the same way as the normal DOM.

Shadow DOM terminology:


•Shadow host: The regular DOM node that the shadow DOM is attached to.
•Shadow tree: The DOM tree inside the shadow DOM.
•Shadow boundary: the place where the shadow DOM ends, and the regular DOM begins.
•Shadow root: The root node of the shadow tree.

ViewEncapsulation ShadowDom

If no encapsulation property is provided, Angular will use Emulated by default. To change to


native Shadow Dom, we can add an encapsulation property and set its value
to ViewEncapsulation.ShadowDom.

Output:
INTRODUCTION TO FORMS IN ANGULAR:
Handling user input with forms is the cornerstone of many common applications. Applications
use forms to enable users to log in, to update a profile, to enter sensitive information, and to
perform many other data-entry tasks.

Angular provides two different approaches to handling user input through forms: reactive and
template-driven. Both capture user input events from the view, validate the user input, create a
form model and data model to update, and provide a way to track changes.

This guide provides information to help you decide which type of form works best for your
situation. It introduces the common building blocks used by both approaches. It also
summarizes the key differences between the two approaches, and demonstrates those
differences in the context of setup, data flow, and testing.
Prerequisites
This guide assumes that you have a basic understanding of the following.
• TypeScript and HTML5 programming
• Angular app-design fundamentals, as described in Angular Concepts
• The basics of Angular template syntax

Choosing an approach
Reactive forms and template-driven forms process and manage form data differently. Each
approach offers different advantages.
FORMS DETAILS
Reactive forms Provide direct, explicit access to the underlying form's
object model. Compared to template-driven forms, they are
more robust: they're more scalable, reusable, and testable. If
forms are a key part of your application, or you're already using
reactive patterns for building your application, use reactive
forms.
Template-driven forms Rely on directives in the template to create and manipulate the
underlying object model. They are useful for adding a simple
form to an app, such as an email list signup form. They're
straightforward to add to an app, but they don't scale as well as
reactive forms. If you have very basic form requirements and
logic that can be managed solely in the template, template-
driven forms could be a good fit

Key differences
The following table summarizes the key differences between reactive and template-driven
forms.
Reactive Template-Driven
Setup of form model Explicit, created in component Implicit, created by directives
class
Data model Structured and immutable Unstructured and mutable
Data flow Synchronous Asynchronous
Form validation Functions Directives

Scalability
If forms are a central part of your application, scalability is very important. Being able to reuse
form models across components is critical.

Reactive forms are more scalable than template-driven forms. They provide direct access to
the underlying form API, and use synchronous data flow between the view and the data model,
which makes creating large-scale forms easier. Reactive forms require less setup for testing,
and testing does not require deep understanding of change detection to properly test form
updates and validation.

Template-driven forms focus on simple scenarios and are not as reusable. They abstract away
the underlying form API, and use asynchronous data flow between the view and the data model.
The abstraction of template-driven forms also affects testing. Tests are deeply reliant on manual
change detection execution to run properly, and require more setup.

Setting up the form models


Both reactive and template-driven forms track value changes between the form input elements
that users interact with and the form data in your component model. The two approaches share
underlying building blocks, but differ in how you create and manage the common form-control
instances.

Common form foundation classes:


Both reactive and template-driven forms are built on the following base classes.
BASIC CLASSES DETAILS
Form Control Tracks the value and validation status of an individual form
control.
Form Group Tracks the same values and status for a collection of form
controls.
Form Array Tracks the same values and status for an array of form controls.
ControlValueAccessor Creates a bridge between Angular FormControl instances and
built-in DOM elements.

Setup in reactive forms


With reactive forms, you define the form model directly in the component class. The
[formControl] directive links the explicitly created FormControl instance to a specific form
element in the view, using an internal value accessor.
The following component implements an input field for a single control, using reactive forms.
In this example, the form model is the FormControl instance.

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


import { FormControl } from '@angular/forms';
@Component({
selector: 'app-reactive-favorite-color',
template: `
Favorite Color: <input type = “text” [formControl]= “favuriteColorControl”>
})
export class FavoriteColorComponent {
favoriteColorControl = new FormControl('');
}
Figure 1 shows how, in reactive forms, the form model is the source of truth; it provides the
value and status of the form element at any given point in time, through the [formControl]
directive on the input element.
Figure 1. Direct access to forms model in a reactive form.

Setup in template-driven forms:


In template-driven forms, the form model is implicit, rather than explicit. The directive
NgModel creates and manages a FormControl instance for a given form element.The following
component implements the same input field for a single control, using template-driven forms

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


@Component({
selector: 'app-template-favorite-color',
template: `
Favorite Color:<input type = “text” [(ngModel)] = “favouriteColor”>
})
export class FavoriteColorComponent
{ favoriteColor = '';
}
In a template-driven form the source of truth is the template. You do not have direct
programmatic access to the FormControl instance, as shown in Figure 2.
Figure 2. Indirect access to forms model in a template-driven form.
Data flow in forms:
When an application contains a form, Angular must keep the view in sync with the component
model and the component model in sync with the view. As users change values and make
selections through the view, the new values must be reflected in the data model. Similarly,
when the program logic changes values in the data model, those values must be reflected in the
view.
Reactive and template-driven forms differ in how they handle data flowing from the user or
from programmatic changes. The following diagrams illustrate both kinds of data flow for each
type of form, using the favorite-color input field defined above.

Data flow in reactive forms :


In reactive forms each form element in the view is directly linked to the form model (a
FormControl instance). Updates from the view to the model and from the model to the view
are synchronous and do not depend on how the UI is rendered.

The view-to-model diagram shows how data flows when an input field's value is changed from
the view through the following steps.
1. The user types a value into the input element, in this case the favorite color Blue.
2. The form input element emits an "input" event with the latest value.
3. The control value accessor listening for events on the form input element immediately relays
the new value to the FormControl instance.
4. The FormControl instance emits the new value through the valueChanges observable.
5. Any subscribers to the valueChanges observable receive the new value.
The model-to-view diagram shows how a programmatic change to the model is propagated to
the view through the following steps.
1. The user calls the favoriteColorControl.setValue() method, which updates the FormControl
value.
2. The FormControl instance emits the new value through the valueChanges observable.
3. Any subscribers to the valueChanges observable receive the new value.
4. The control value accessor on the form input element updates the element with the new
value.
Data flow in template-driven forms:
In template-driven forms, each form element is linked to a directive that manages the form
model internally.
The view-to-model diagram shows how data flows when an input field's value is changed from
the view through the following steps.
1. The user types Blue into the input element.
2. The input element emits an "input" event with the value Blue.
3. The control value accessor attached to the input triggers the setValue() method on the
FormControl instance.
4. The FormControl instance emits the new value through the valueChanges observable.
5. Any subscribers to the valueChanges observable receive the new value.
6. The control value accessor also calls the NgModel.viewToModelUpdate() method which
emits an ngModelChange event.
7. Because the component template uses two-way data binding for the favoriteColor property,
the favoriteColor property in the component is updated to the value emitted by the
ngModelChange event (Blue).

The model-to-view diagram shows how data flows from model to view when the favoriteColor
changes from Blue to Red, through the following steps
1. The favoriteColor value is updated in the component.
2. Change detection begins.
3. During change detection, the ngOnChanges lifecycle hook is called on the NgModel
directive instance because the value of one of its inputs has changed.
4. The ngOnChanges() method queues an async task to set the value for the internal
FormControl instance.
5. Change detection completes.
6. On the next tick, the task to set the FormControl instance value is executed.
7. The FormControl instance emits the latest value through the valueChanges observable.
8. Any subscribers to the valueChanges observable receive the new value.
9. The control value accessor updates the form input element in the view with the latest
favoriteColor value.

Mutability of the data model:


The change-tracking method plays a role in the efficiency of your application.
forms Details
Reactive forms Keep the data model pure by providing it as an immutable data
structure. Each time a change is triggered on the data model, the
FormControl instance returns a new data model rather than
updating the existing data model. This gives you the ability to track
unique changes to the data model through the control's observable.
Change detection is more efficient because it only needs to update
on unique changes. Because data updates follow reactive patterns,
you can integrate with observable operators to transform data.
Template-driven forms Rely on mutability with two-way data binding to update the data
model in the component as changes are made in the template.
Because there are no unique changes to track on the data model
when using two-way data binding, change detection is less efficient
at determining when updates are required.

The difference is demonstrated in the previous examples that use the favorite-color input
element.
• With reactive forms, the FormControl instance always returns a new value when the control's
value is updated
• With template-driven forms, the favorite color property is always modified to its new value
Form validation:
Validation is an integral part of managing any set of forms. Whether you're checking for
required fields or querying an external API for an existing username, Angular provides a set of
built-in validators as well as the ability to create custom validators.
Forms Details
Reactive forms Define custom validators as functions that receive a control to
validate
Template-driven Tied to template directives, and must provide custom validator
forms directives that wrap validation functions

Testing:
Testing plays a large part in complex applications. A simpler testing strategy is useful when
validating that your forms function correctly. Reactive forms and template-driven forms have
different levels of reliance on rendering the UI to perform assertions based on form control and
form field changes. The following examples demonstrate the process of testing forms with
reactive and template-driven forms.

Testing reactive forms:


Reactive forms provide a relatively straightforward testing strategy because they provide
synchronous access to the form and data models, and they can be tested without rendering the
UI. In these tests, status and data are queried and manipulated through the control without
interacting with the change detection cycle.
The following tests use the favorite-color components from previous examples to verify the
view-to-model and model-to-view data flows for a reactive form.

Verifying view-to-model data flow


The first example performs the following steps to verify the view-to-model data flow.
1. Query the view for the form input element, and create a custom "input" event for the test.
2. Set the new value for the input to Red, and dispatch the "input" event on the form input
element.
3. Assert that the component's favoriteColorControl value matches the value from the input.
4. it('should update the value of the input field', () => {
5. const input = fixture.nativeElement.querySelector('input');
6. const event = createNewEvent('input');
7.
8. input.value = 'Red';
9. input.dispatchEvent(event);
10.
11. expect(fixture.componentInstance.favoriteColorControl.value).toEqual('Red');
12. });
The next example performs the following steps to verify the model-to-view data flow.
1. Use the favoriteColorControl, a FormControl instance, to set the new value.
2. Query the view for the form input element.
3. Assert that the new value set on the control matches the value in the input.
4. it('should update the value in the control', () => {
5. component.favoriteColorControl.setValue('Blue');
6.
7. const input = fixture.nativeElement.querySelector('input');
8.
9. expect(input.value).toBe('Blue');
10.
});
Testing template-driven forms:
Writing tests with template-driven forms requires a detailed knowledge of the change detection
process and an understanding of how directives run on each cycle to ensure that elements are
queried, tested, or changed at the correct time.
The following tests use the favorite color components mentioned earlier to verify the data flows
from view to model and model to view for a template-driven form.

The following test verifies the data flow from view to model.
it('should update the favorite color in the component', fakeAsync(() => {
const input = fixture.nativeElement.querySelector('input');
const event = createNewEvent('input');
input.value = 'Red';
input.dispatchEvent(event);
fixture.detectChanges();
expect(component.favoriteColor).toEqual('Red');
}));
Here are the steps performed in the view to model test.
1. Query the view for the form input element, and create a custom "input" event for the test.
2. Set the new value for the input to Red, and dispatch the "input" event on the form input
element.
3. Run change detection through the test fixture.
4. Assert that the component favoriteColor property value matches the value from the input.

The following test verifies the data flow from model to view.
it('should update the favorite color on the input field', fakeAsync(() => {
component.favoriteColor = 'Blue';
fixture.detectChanges();
tick();
const input = fixture.nativeElement.querySelector('input');
expect(input.value).toBe('Blue'); }));

Here are the steps performed in the model to view test.


1. Use the component instance to set the value of the favoriteColor property.
2. Run change detection through the test fixture.
3. Use the tick() method to simulate the passage of time within the fakeAsync() task.
4. Query the view for the form input element.
5. Assert that the input value matches the value of the favoriteColor property in the component
instance.
DEPENDENCY INJECTION:
Dependency injection is a core feature of the Angular framework. It is a way to manage the
dependencies between different components in your application by providing a centralized
location for the creation and management of these dependencies.

In Angular, the @Injectable decorator is used to mark a class as a candidate for dependency
injection. This decorator allows you to specify the dependencies that a class needs as
constructor parameters, and Angular will automatically inject these dependencies when an
instance of the class is created.

Here's an example of how to use dependency injection in Angular:

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

import { HttpClient } from '@angular/common/http';

@Injectable({

providedIn: 'root'

})

export class ProductService {

constructor(private http: HttpClient) { }

getAllProducts() {

return this.http.get('/api/products');

In this example, we have defined a ProductService class and marked it with the @Injectable
decorator. The providedIn property of the decorator specifies that the service should be
provided in the root injector of the application.
The ProductService class has a constructor that takes an instance of the HttpClient class as a
parameter. This is an example of dependency injection, as Angular will automatically inject an
instance of the HttpClient class into the ProductService class when it is created.

To use the ProductService class in another component, you can simply add it as a constructor
parameter:

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

import { ProductService } from './product.service';

@Component({

selector: 'app-products',

template: `

<h1>Products</h1>

<ul>

<li *ngFor="let product of products">{{ product.name }}</li>

</ul>

})

export class ProductsComponent {

products: any[];

constructor(private productService: ProductService) { }

ngOnInit() {

this.productService.getAllProducts().subscribe((data: any[]) => {

this.products = data;
});

In this example, we have defined a ProductsComponent that uses the ProductService class
to retrieve a list of products. The ProductService class is added as a constructor parameter,
and Angular will automatically inject an instance of the ProductService class into the
ProductsComponent class when it is created.

With dependency injection, you can easily manage the dependencies between different
components in your Angular application, making it more modular and easier to maintain.

SERVICES BASICS:

In Angular, a service is a class that provides some functionality to your application. Services
are typically used to provide data and functionality that can be shared across multiple
components in your application.

To create a service in Angular, you can use the @Injectable decorator to mark a class as a
service:

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

@Injectable({

providedIn: 'root'

})

export class ProductService {

// service code goes here

}
In this example, we have defined a ProductService class and marked it as a service using the
@Injectable decorator. The providedIn property of the decorator specifies that the service
should be provided in the root injector of the application.

Once you have defined a service, you can use it in your components by adding it as a
constructor parameter:

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

import { ProductService } from './product.service';

@Component({

selector: 'app-products',

template: `

<h1>Products</h1>

<ul>

<li *ngFor="let product of products">{{ product.name }}</li>

</ul>

})

export class ProductsComponent {

products: any[];

constructor(private productService: ProductService) { }

ngOnInit() {

this.products = this.productService.getProducts();

}
}

In this example, we have defined a ProductsComponent that uses the ProductService class
to retrieve a list of products. The ProductService class is added as a constructor parameter,
and Angular will automatically inject an instance of the ProductService class into the
ProductsComponent class when it is created.

Services can also be used to make HTTP requests and retrieve data from external sources. For
example:

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

import { HttpClient } from '@angular/common/http';

@Injectable({

providedIn: 'root'

})

export class ProductService {

constructor(private http: HttpClient) { }

getAllProducts() {

return this.http.get('/api/products');

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

import { HttpClient } from '@angular/common/http';

@Injectable({

providedIn: 'root'
})

export class ProductService {

constructor(private http: HttpClient) { }

getAllProducts() {

return this.http.get('/api/products');

In this example, we have defined a ProductService class that uses the HttpClient class to
make an HTTP request to retrieve a list of products. The HttpClient class is added as a
constructor parameter, and Angular will automatically inject an instance of the HttpClient
class into the ProductService class when it is created.

Services are a powerful feature of Angular that allow you to centralize functionality and data
that can be shared across multiple components in your application.

RxJX OBSERVABLES:

RxJS Observables are an essential part of Angular development. They provide a powerful way
to handle asynchronous operations and manage data streams. Observables are used extensively
in Angular to handle HTTP requests, form events, user input, and other asynchronous
operations.

Observables are essentially a sequence of values over time that can be observed. Observables
can emit multiple values over time, and each value is delivered to subscribers. Observables can
be created using the Observable class provided by RxJS.

Here's an example of an Observable in Angular:

import { Component, OnInit } from '@angular/core';

import { Observable } from 'rxjs';


@Component({

selector: 'app-example',

template: `

<div *ngFor="let number of numbers">{{ number }}</div>

})

export class ExampleComponent implements OnInit {

numbers$: Observable<number[]>;

ngOnInit() {

this.numbers$ = Observable.create(observer => {

observer.next([1, 2, 3]);

observer.next([4, 5, 6]);

observer.next([7, 8, 9]);

observer.complete();

});

In this example, we have defined an ExampleComponent that uses an Observable to emit a


sequence of numbers. The Observable is created using the Observable.create() method, which
takes an observer object as an argument. The observer object is used to emit values and notify
subscribers when the Observable is complete.
In the ngOnInit() method of the ExampleComponent, we create an Observable that emits
three arrays of numbers. The numbers$ property is of type Observable<number[]>, and it is
used in the template to display the emitted values.

Observables are also used extensively in Angular to handle HTTP requests. Here's an example
of an Observable that makes an HTTP request:

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

import { HttpClient } from '@angular/common/http';

import { Observable } from 'rxjs';

@Injectable({

providedIn: 'root'

})

export class ProductService {

constructor(private http: HttpClient) { }

getProducts(): Observable<Product[]> {

return this.http.get<Product[]>('/api/products');

In this example, we have defined a ProductService that uses an Observable to retrieve a list
of products from a web API. The getProducts() method returns an Observable of type
Product[], which is obtained by making an HTTP GET request to the /api/products endpoint
using the HttpClient service provided by Angular.

Overall, Observables are an essential part of Angular development, and they provide a powerful
way to handle asynchronous operations and manage data streams.
SERVER COMMUNICATION THROUGH HTTP CLIENT:

To communicate with a server through an HTTP client in Angular, you can use Angular's built-
in HttpClient module. The HttpClient module provides a simplified API for making HTTP
requests and handling their responses.

Here is a simple example of how to use HttpClient to make a GET request to an API endpoint:

1. Import the HttpClient module in your component:


import { HttpClient } from '@angular/common/http';

2. Inject the HttpClient service into your component's constructor:

constructor(private http: HttpClient) { }


3. Use the http.get() method to make a GET request to an API endpoint:

this.http.get('https://api.example.com/data').subscribe(data => {

console.log(data);

});

In this example, we are making a GET request to the 'https://api.example.com/data' endpoint


and subscribing to the Observable returned by the http.get() method. When the server responds
with data, the callback function passed to the subscribe() method will be called with the
response data.

You can also pass options to the http.get() method, such as query parameters or request headers,
using the HttpParams and HttpHeaders classes provided by the HttpClient module.

Similarly, you can use the http.post() method to make a POST request, http.put() method to
make a PUT request, and so on.

communicating with different backend services using angular httpclient

To communicate with different backend services using Angular HttpClient, you can make use
of the HTTP methods provided by the HttpClient module.
Here's an example of how you can use HttpClient to communicate with different backend
services:

1. Import HttpClient and HttpHeaders:

import { HttpClient, HttpHeaders } from '@angular/common/http';

2. Inject the HttpClient service into your component:

constructor(private http: HttpClient) { }

3. Define the HTTP headers for your request:

const httpOptions = {

headers: new HttpHeaders({

'Content-Type': 'application/json'

})

};

4. Make an HTTP GET request to fetch data from a REST API:

this.http.get('https://api.example.com/data', httpOptions).subscribe(data => {

console.log(data);

});

n this example, we are making a GET request to the 'https://api.example.com/data' endpoint


and passing the HTTP headers defined in httpOptions as the second argument.

5. Make an HTTP POST request to create new data:

const postData = {

name: 'John Doe',

email: 'johndoe@example.com'
};

this.http.post('https://api.example.com/create', postData, httpOptions).subscribe(data => {

console.log(data);

});

In this example, we are making a POST request to the 'https://api.example.com/create' endpoint


with the data to be created, and passing the HTTP headers defined in httpOptions as the third
argument.

You can similarly use the http.put() method to update data, http.delete() method to delete data,
and so on.

Note that the specific implementation of these methods may vary depending on the backend
service you are communicating with. You may need to pass additional parameters, such as
query parameters or authentication tokens, as required by the backend service's API.

ROUTER BASICS:

In Angular, the Router module provides a powerful and flexible way to handle navigation and
routing in your application. Here are some basics of using the Router module:

1. Import the RouterModule and Routes from the @angular/router module in your
app.module.ts file:

import { RouterModule, Routes } from '@angular/router';

2. Define your routes as an array of objects. Each route object should have a path property
that specifies the URL path and a component property that specifies the component to
be displayed when the URL path is matched:

const routes: Routes = [

{ path: '', component: HomeComponent },


{ path: 'about', component: AboutComponent },

{ path: 'contact', component: ContactComponent },

{ path: '**', component: NotFoundComponent }

];

In this example, we have defined four routes: one for the home page, one for the about page,
one for the contact page, and one for handling any other URL paths that do not match the
defined routes.

3. Add the RouterModule to the imports array in your app.module.ts file and call the
forRoot() method to initialize the router with your routes:

@NgModule({

imports: [RouterModule.forRoot(routes)],

exports: [RouterModule]

})

export class AppModule { }

4. In your app.component.html file, add a <router-outlet></router-outlet> tag to display


the routed components:

<router-outlet></router-outlet>

5. Use the RouterLink directive to create links to your routes in your component
templates:

<a routerLink="/">Home</a>

<a routerLink="/about">About</a>

<a routerLink="/contact">Contact</a>
In this example, we are using the routerLink directive to create links to the home, about, and
contact routes.

6. Use the router.navigate() method in your component code to programmatically navigate


to a route:

import { Router } from '@angular/router'

constructor(private router: Router) {}

goToAboutPage() {

this.router.navigate(['/about']);

In this example, we are injecting the Router service into our component and defining a method
that navigates to the about route when called.

These are some basic concepts of using the Router module in Angular. Once you have a good
understanding of these basics, you can explore more advanced features such as child routes,
route parameters, and route guards.

ROUTE LINKS:

In Angular, you can use the routerLink directive to create links to routes in your application.
Here are some examples of how to use routerLink:

1. Basic link:

<a routerLink="/">Home</a>

This creates a link to the home route, which typically maps to an HomeComponent.

2. Link with parameters:

<a routerLink="/product/{{productId}}">Product Details</a>


This creates a link to the product details route, where productId is a variable that contains the
ID of the product you want to display. In the component that displays the product details, you
can access this ID using the ActivatedRoute service.

3. Relative link:

<a routerLink="../">Go Back</a>

This creates a link that navigates up one level in the route hierarchy. For example, if you are
currently at the route /products/123/details, this link would navigate to the /products/123
route.

4. Query parameters:

<a [routerLink]="['/search']" [queryParams]="{q: 'angular'}">Search</a>

This creates a link to the search route and sets the query parameter q to the value angular. In
the component that displays the search results, you can access this value using the
ActivatedRoute service.

Note that you can also use the router.navigate() method in your component code to
programmatically navigate to a route, and you can use the ActivatedRoute service to access
route parameters and query parameters in your component code.

ROUTE GAURDS:

In Angular, route guards are used to control access to routes based on certain conditions. There
are several types of route guards:

1. CanActivate: This guard is used to control access to a route based on whether the user
is authorized to access it. If the user is authorized, the guard allows access to the route.
If the user is not authorized, the guard redirects the user to a different route.

Example:

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


import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from
'@angular/router';

import { Observable } from 'rxjs';

import { AuthService } from './auth.service';

@Injectable({

providedIn: 'root'

})

export class AuthGuard implements CanActivate {

constructor(private authService: AuthService, private router: Router) {}

canActivate(

next: ActivatedRouteSnapshot,

state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree>


| boolean | UrlTree {

if (this.authService.isLoggedIn()) {

return true;

} else {

this.router.navigate(['/login']);

return false;

}
In this example, we have defined an AuthGuard that implements the CanActivate interface.
The guard checks whether the user is logged in using an AuthService, and if not, it redirects
the user to the login page.

2. CanDeactivate: This guard is used to control whether the user can navigate away from
a route that has unsaved changes. If the user has made changes, the guard prompts the
user to confirm whether they want to discard the changes before navigating away from
the route.

Example:

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

import { CanDeactivate } from '@angular/router';

import { Observable } from 'rxjs';

import { ComponentCanDeactivate } from './component-can-deactivate';

@Injectable({

providedIn: 'root'

})

export class ConfirmDeactivateGuard implements


CanDeactivate<ComponentCanDeactivate> {

canDeactivate(component: ComponentCanDeactivate): Observable<boolean> |


Promise<boolean> | boolean {

return component.canDeactivate();

In this example, we have defined a ConfirmDeactivateGuard that implements the


CanDeactivate interface. The guard calls a canDeactivate() method on the component that
implements a ComponentCanDeactivate interface. If the method returns true, the guard
allows navigation away from the route. If the method returns false, the guard prompts the user
to confirm whether they want to discard the changes before navigating away from the route.

3. CanLoad: This guard is used to control whether the application should load a lazy-
loaded module. If the guard returns true, the module is loaded. If the guard returns
false, the module is not loaded.

Example:

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

import { CanLoad, Route, UrlSegment } from '@angular/router';

import { Observable } from 'rxjs';

import { AuthService } from './auth.service';

@Injectable({

providedIn: 'root'

})

export class AuthLoadGuard implements CanLoad {

constructor(private authService: AuthService) {}

canLoad(

route: Route,

segments: UrlSegment[]): Observable<boolean> | Promise<boolean> | boolean {

return this.authService.isLoggedIn();

In this example, we have defined an AuthLoadGuard that implements the CanLoad interface.
The guard checks whether the user is logged in using an AuthService, and if so, it allows
loading of the lazy-loaded module. If the user is not logged in, the guard prevents loading of
the module.

These are some basic examples of using route guards in Angular. Once you have a good
understanding of these basics, you can explore more advanced features such as canActivate

ASYNCHRONOUS ROUTING:

In Angular, asynchronous routing is a feature that allows you to load route configuration data
asynchronously. This can be useful if you have a large application with many routes, and you
want to improve performance by loading the route configuration data only when it is needed.

To implement asynchronous routing in Angular, you can use the loadChildren property in
your route configuration. The loadChildren property is a string that specifies the path to a
module that exports a NgModuleFactory or a Promise that resolves to a NgModuleFactory.
The module should contain the routes for the lazy-loaded module.

Here's an example of how to implement asynchronous routing in Angular:

const routes: Routes = [

{ path: '', redirectTo: '/home', pathMatch: 'full' },

{ path: 'home', component: HomeComponent },

path: 'lazy',

loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule)

},

{ path: '**', component: PageNotFoundComponent }

];

In this example, we have defined a lazy route that loads the LazyModule module using the
loadChildren property. The import() function returns a Promise that resolves to the
LazyModule module, and the then() method returns the NgModuleFactory for the module.
When the user navigates to the lazy route, Angular will load the LazyModule module
asynchronously and then activate the corresponding route. This can improve performance by
reducing the initial loading time of your application.

It's important to note that asynchronous routing requires the use of lazy-loaded modules, which
can add complexity to your application. However, if used properly, asynchronous routing can
be a powerful tool for improving the performance of your Angular application.

NESTED ROUTES:

In Angular, you can define nested routes to organize your application into smaller, more
manageable modules. Nested routes are routes that are defined within other routes, allowing
you to create hierarchical navigation structures.

To define nested routes in Angular, you need to use the children property in your route
configuration. The children property is an array of child routes, each of which can have its
own child routes.

Here's an example of how to define nested routes in Angular:

const routes: Routes = [

{ path: '', redirectTo: '/home', pathMatch: 'full' },

{ path: 'home', component: HomeComponent },

path: 'products',

component: ProductsComponent,

children: [

{ path: '', redirectTo: 'all', pathMatch: 'full' },

{ path: 'all', component: AllProductsComponent },

{ path: 'category/:categoryName', component: CategoryProductsComponent },

{ path: ':id', component: ProductDetailComponent }


]

},

{ path: '**', component: PageNotFoundComponent }

];

In this example, we have defined a products route that has four child routes defined in the
children property. The '' path in the products route redirects to the all path, which displays
all the products. The category/:categoryName path displays products based on their category
name, and the :id path displays the details of a specific product.

To navigate to a nested route, you can use the routerLink directive in your HTML template.
Here's an example:

<a routerLink="/products/all">All Products</a>

<a routerLink="/products/category/shoes">Shoes</a>

<a routerLink="/products/1">Product 1</a>

In this example, we have used the routerLink directive to create links to the all and
category/:categoryName paths in the products route, as well as the :id path for a specific
product.

With nested routes, you can create complex navigation structures that make it easy for users to
navigate through your application.

You might also like