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

UNIT –I: Introduction to Angular JS

[06L] Max Marks:08


1.1 What is Angular JS? Advantages and Disadvantages of Angular JS

1.1 .1 What is Angular JS?


AngularJS is an open source, JavaScript based web application development
framework. Definition of AngularJS as put by its official documentation is as follows:
AngularJS is a structural framework for dynamic web applications. It lets you use HTML
as your template language and lets you extend HTML's syntax to express your
application components clearly and succinctly. Its data binding and dependency
injection eliminate much of the code you currently have to write. And it all happens
within the browser, making it an ideal partner with any server technology. It was
originally developed in 2009 by Misko Hevery and Adam Abrons. It is now maintained
by Google.

1.1.2 Advantages and Disadvantages of Angular JS:


Advantages:
● AngularJS provides capability to create Single Page Application in a very clean
and maintainable way.
● AngularJS provides data binding capability to HTML. Thus, it gives user a rich
and responsive experience.
● AngularJS code is unit testable.
● AngularJS uses dependency injection and make use of separation of concerns.
AngularJS provides reusable components.
● With AngularJS, the developers can achieve more functionality with short code.
● In AngularJS, views are pure html pages, and controllers written in JavaScript do
the business processing.

Disadvantages:
Though AngularJS comes with a lot of merits, here are some points of concern:
● Not Secure : Being JavaScript only framework, application written in AngularJS
are not safe. Server side authentication and authorization is must to keep an
application secure.
● Not degradable: If the user of your application disables JavaScript, then nothing
would be visible, except the basic page.

1.2 Features of Angular JS:


The most important general features of AngularJS are.
● AngularJS is a efficient framework that can create Rich Internet Applications
(RIA)
● AngularJS provides developers an options to write client side applications using
JavaScript in a clean Model View Controller (MVC) way.
● Applications written in AngularJS are cross-browser compliant. AngularJS
automatically handles JavaScript code suitable for each browser.
● AngularJS is open source, completely free, and used by thousands of developers
around the world. It is licensed under the Apache license version 2.0.

Core Features:
● Data-binding: It is the automatic synchronization of data between model and view
components.
● Scope: These are objects that refer to the model. They act as a glue between
controller and view.
● Controller: These are JavaScript functions bound to a particular scope.
● Services: AngularJS comes with several built-in services such as $http to make
a XMLHttpRequests. These are singleton objects which are instantiated only
once in app.
● Filters: These select a subset of items from an array and returns a new array.
● Directives: Directives are markers on DOM elements such as elements,
attributes, css, and more. These can be used to create custom HTML tags that
serve as new, custom widgets. AngularJS has built-in directives such as ngBind,
ngModel etc.
● Templates:These are the rendered view with information from the controller and
model. These can be a single file (such as index.html) or multiple views in one
page using partials.
● Routing: It is concept of switching views.
● Model View Whatever: MVW is a design pattern for dividing an application into
different parts called Model, View, and Controller, each with distinct
responsibilities. AngularJS does not implement MVC in the traditional sense, but
rather something closer to MVVM (Model-View-ViewModel). The Angular JS
team refers it humorously as Model View Whatever.
● Deep Linking: Deep linking allows you to encode the state of application in the
URL so that it can be bookmarked. The application can then be restored from the
URL to the same state.
● Dependency Injection: AngularJS has a built-in dependency injection subsystem
that helps the developer to create,understand, and test the applications easily.

1.3 AngularJS Directives :


The AngularJS framework can be divided into three major parts:
○ ng-app : This directive defines and links an AngularJS application to
HTML.
○ ng-model : This directive binds the values of AngularJS application data
to HTML input controls.
○ ng-bind : This directive binds the AngularJS application data to HTML
tags.
Angular CLI (Command Line Interface) is a command-line tool provided by the Angular
team for creating, managing, and maintaining Angular applications. It simplifies the
development process by automating repetitive tasks such as project setup, component
generation, testing, and deployment.

1.4 angular cli and troubleshooting


Here's an overview of what Angular CLI offers:

● Project Scaffolding: Angular CLI allows you to quickly create a new Angular
project structure with all the necessary files and configurations using a single
command.
● Code Generation: It provides commands to generate various Angular
components, services, modules, directives, pipes, and more. This helps in
following best practices and maintaining consistency in code structure.
● Development Server: Angular CLI includes a built-in development server that
allows you to run your application locally for development and testing purposes.
Changes to your code are automatically reflected in the browser without needing
to manually reload the page.
● Build Optimization: Angular CLI optimizes your application for production
deployment by generating optimized bundles, minifying and uglifying code, and
performing tree shaking to remove unused code.
● Testing Utilities: Angular CLI integrates with testing frameworks like Karma and
Jasmine to facilitate unit testing and end-to-end testing of Angular applications. It
provides commands to run tests and generate code coverage reports.
● Deployment: Angular CLI offers commands to build your application for
deployment to various hosting platforms. It optimizes your application for
production and generates static files that can be deployed to a web server or
cloud hosting service.

When it comes to troubleshooting Angular CLI, here are some common issues you
might encounter and how to address them:

● Installation Issues: If you encounter problems during Angular CLI installation,


ensure that you have the correct versions of Node.js and npm installed. You can
also try installing Angular CLI globally using npm:
npm install -g @angular/cli
● Command Execution Errors: If commands like ng new, ng generate, or ng serve
fail to execute, double-check your project structure, file permissions, and system
environment variables. Ensure that you are running the commands from the
correct directory.
● Dependency Conflicts: Angular CLI projects rely on specific versions of
dependencies. If you encounter dependency conflicts or errors, try updating your
project's dependencies or reinstalling them using npm install.
● Build Failures: If your application fails to build or encounters errors during the
build process, carefully review the error messages in the terminal for clues.
Common issues include syntax errors, missing dependencies, or misconfigured
build settings.
● Performance Issues: If Angular CLI commands are slow to execute or your
application performance is poor, consider optimizing your project configuration,
dependencies, or build settings. You can also try clearing the Angular CLI cache
using npm cache clean --force.
● Community Resources: If you're unable to resolve a specific issue, consult online
forums, GitHub repositories, or community channels dedicated to Angular
development. Other developers may have encountered similar problems and
provided solutions or workarounds.

1.5 Node JavaScript Introduction


What is Node.js?

● Node.js is an open source server environment


● Node.js is free
● Node.js runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
● Node.js uses JavaScript on the server

Node.js is an open-source, cross-platform JavaScript runtime environment that


allows developers to run JavaScript code outside of a web browser. It uses the
V8 JavaScript engine, which is the same engine that powers Google Chrome, to
execute JavaScript code on the server-side.

Here's a brief introduction to Node.js and its key features:

● JavaScript Runtime: Node.js enables you to execute JavaScript code on


the server-side, allowing for the development of server-side applications,
command-line tools, and more.
● Asynchronous, Event-Driven Architecture: One of the core principles of
Node.js is its non-blocking, asynchronous I/O model. This means that
Node.js can handle many concurrent connections efficiently without
getting blocked, making it ideal for building highly scalable and
performant applications.
● NPM (Node Package Manager): Node.js comes bundled with npm, a
package manager for JavaScript libraries and tools. npm provides access
to a vast ecosystem of reusable packages that developers can use to
enhance their applications and streamline development workflows.
● Single-Threaded, Event Loop: Node.js operates on a single-threaded
event loop, which means that it can handle multiple requests concurrently
without creating additional threads. The event loop manages
asynchronous operations and callbacks, allowing Node.js to handle
I/O-intensive tasks efficiently.
● Built-in Modules: Node.js provides a set of core modules that offer
essential functionality for building server-side applications, such as HTTP,
File System, Path, and more. These modules enable developers to
perform common tasks without relying on external dependencies.
● Cross-Platform Compatibility: Node.js is compatible with various operating
systems, including Windows, macOS, and Linux, making it easy to
develop and deploy applications across different environments.
● Community and Ecosystem: Node.js has a vibrant and active community
of developers who contribute to the ecosystem by creating libraries,
frameworks, tools, and resources. This thriving ecosystem makes it easy
for developers to find solutions to common problems and accelerate the
development process.

To get started with Node.js, you'll need to install it on your machine. You can
download the Node.js installer from the official Node.js website
(https://nodejs.org) and follow the installation instructions for your operating
system.

1.6 Setup Node js with angular

In this section, we’ll guide you through the process of installing Angular on a Windows
machine. Follow the steps below to get Angular up and running on your system:
Step 1: Install Node.js and npm
Step 2: Install Angular CLI Globally
Step 3: Run Angular CLI Commands
Step 4: Create an Initial Workspace for the Application
Step 5: Run the Angular Application in Your Browser
● Step 1: Install Node.js and npm
Before you can install Angular, you’ll need to have Node.js and npm (Node Package
Manager) installed on your machine. Again, if you haven’t already installed them, follow
the instructions in our guide on how to install Node.js.
● Step 2: Install Angular CLI Globally
Next, you’ll need to install the Angular CLI tool. To install the Angular CLI globally on
your system, open the Command Prompt and run the following command:
npm install -g @angular/cli
This command installs the latest stable version of the Angular CLI tool and makes it
available for use throughout your system.
● Step 3: Run Angular CLI Commands
Once you have the Angular CLI installed, you can use its commands to manage your
Angular projects. To verify that the installation was successful, run the following
command in the Command Prompt:
ng --version
This command displays the installed version of the Angular CLI, along with other
relevant information about your environment.

● Step 4: Create an Initial Workspace for the Application

To create a new Angular application, you’ll need to create a workspace. A workspace is


a directory that contains the configuration files and source code for your Angular
projects. To create a new workspace, run the following command in the Command
Prompt, replacing my-app with the desired name for your application:
ng new my-app
This command creates a new directory with the specified name, sets up the necessary
configuration files, and generates an initial Angular application within the workspace.

● Step 5: Run the Angular Application in Your Browser


To test your new Angular application, navigate to the newly created directory using the
cd command:
cd my-app
Then, start the development server by running the following command:
ng serve
This command compiles your Angular application and starts a development server. By
default, the server runs on port 4200.
Open your preferred web browser and navigate to http://localhost:4200/. You should
see your new Angular application running in the browser.

1.7 Typescript Introduction


TypeScript is an open-source, object-oriented programming language
developed and maintained by Microsoft Corporation. Its journey began in 2012,
and since then, it has gained significant traction in the developer community. It is
a Strict Super Set of JavaScript, which means anything implemented in
JavaScript can be implemented using TypeScript along with adding enhanced
features (every existing JavaScript Code is a valid TypeScript Code). As
TypeScript code is converted to JavaScript code it makes it easier to integrate
into JavaScript projects. It is designed mainly for large-scale projects.

1.8 What is bootstrap


Bootstrap is a widely-used open-source front-end framework for web development,
providing a collection of HTML, CSS, and JavaScript components and tools that enable
developers to build responsive, mobile-first websites with ease.
This Bootstrap tutorial is designd for beginners and experienced professional, overing
basics and advanced concepts including including working with Bootstrap’s CSS
classes, incorporating JavaScript plugins, and more. This tutorial will help you with the
knowledge and skills to create stunning and responsive websites.

By the end of this tutorial, you’ll have a solid understanding of Bootstrap’s capabilities
and be able to apply them effectively in your web development projects.
Bootstrap is a free and open-source tool collection for creating responsive websites and

web applications. It is the most popular HTML, CSS, and JavaScript framework for

developing responsive, mobile-first websites. Nowadays, the websites are perfect for all

browsers (IE, Firefox, and Chrome) and for all sizes of screens (Desktop, Tablets,

Phablets, and Phones). All thanks to Bootstrap developers – Mark Otto and Jacob

Thornton of Twitter, though it was later declared to be an open-source project.

1.8 How AngularJS Integrates with HTML

● AngularJS extends HTML with ng-directives.


● The ng-app directive defines an AngularJS application.
● The ng-model directive binds the value of HTML controls (input, select,
textarea) to application data.
● The ng-bind directive binds application data to the HTML view.

<!DOCTYPE html>

<html>

<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.mi
n.js"></script>

<body>

<div ng-app="">
<p>Name: <input type="text" ng-model="name"></p>

<p ng-bind="name"></p>

</div>

</body>

</html>

Example explained:

● AngularJS starts automatically when the web page has loaded.


● The ng-app directive tells AngularJS that the <div> element is the
"owner" of an AngularJS application.
● The ng-model directive binds the value of the input field to the application
variable name.
● The ng-bind directive binds the content of the <p> element to the
application variable name.

1.9 Creating AngularJS Application

● Step 1: Load framework

Being a pure JavaScript framework, it can be added using <Script> tag.

<script

src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">

</script>

● Step 2: Define AngularJS application using ng-app directive

<div ng-app = "">

...

</div>

● Step 3: Define a model name using ng-model directive

<p>Enter your Name: <input type = "text" ng-model = "name"></p>

● Step 4: Bind the value of above model defined using ng-bind directive
<p>Hello <span ng-bind = "name"></span>!</p>

Executing AngularJS Application

Use the above-mentioned three steps in an HTML page.

testAngularJS.htm

Live Demo

<html>

<head>

<title>AngularJS First Application</title>

</head>

<body>

<h1>Sample Application</h1>

<div ng-app = "">

<p>Enter your Name: <input type = "text" ng-model = "name"></p>

<p>Hello <span ng-bind = "name"></span>!</p>

</div>

<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">

</script>

</body>

</html>

Output

Open the file testAngularJS.htm in a web browser. Enter your name and see the result.

****************************************************************************************************
UNIT –II: Modules and Components, Data Binding in Angular JS

[10L] Max Marks: 12

2.1 What is Component in Angular JS,

Here are the key characteristics of a component in AngularJS:

● Encapsulation: Components encapsulate the HTML markup, CSS styles, and


JavaScript logic related to a specific UI element or feature. This encapsulation
ensures that the component's implementation details are isolated from the rest of
the application, promoting modularity and reusability.
● Template: Each component has a template that defines its HTML structure and
layout. The template may include dynamic content, data bindings, directives, and
other AngularJS constructs. Templates can be defined inline within the
component's metadata or loaded from external files.
● Controller: Components have an associated controller or controller function that
contains the logic and behavior of the component. The controller interacts with
the component's view (template) and model (data) to handle user interactions,
update the UI, and perform business logic.
● Scope: Components have their own scope, which is a JavaScript object that
contains the data and functions accessible to the component's template and
controller. The scope allows components to maintain state, share data with child
components, and trigger updates to the UI.
● Directives: Components can use AngularJS directives to enhance their
functionality or extend HTML with custom behavior. Directives such as ng-model,
ng-click, ng-show, etc., can be applied within a component's template to enable
data binding, event handling, and DOM manipulation.
● Lifecycle Hooks: AngularJS components have lifecycle hooks that allow
developers to execute code at specific stages of a component's lifecycle, such as
initialization, rendering, destruction, etc. These hooks provide opportunities to
perform setup, cleanup, or side effects during the component's lifecycle.
● Dependency Injection: Components can declare dependencies on other
AngularJS services, such as services, factories, providers, etc. Dependency
injection allows components to access external functionality, share resources,
and promote separation of concerns.

2.2 what is Module in Angular JS,

The AngularJS module defines the functionality of the application which is


applied on the entire HTML page. It helps to link many components. So it is just a
group of related components. It is a container that consists of different parts like
controllers, services, and directives.
Note: These modules should be made in normal HTML files like index.html and
no need to create a new project in VisualStudio for this section.
Creating a Module in AngularJS:
var app = angular.module("Module-name", []);
In this [], we can add a list of components needed but we are not including any
components in this case. This created module is bound with any tag like div,
body, etc by adding it to the list of modules.
<div ng-app = "module-name">
The code in which the module is required.
</div>

Adding a Controller:
app.controller("Controller-name", function($scope) {
$scope.variable-name= "";
});
In AngularJS, a module is a container for the different components of an
application, such as controllers, services, directives, filters, and configuration
blocks. Modules help in organizing and structuring an AngularJS application by
providing a cohesive and modular approach to development.

Here are the key aspects of modules in AngularJS:

● Container for Components: Modules act as containers that hold related


components of an AngularJS application. These components can include
controllers, services, directives, filters, and other modules.
● Dependency Management: Modules define the dependencies between
different components of an application. By specifying dependencies,
modules allow components to be easily injected and used within other
components. This promotes modularity, reusability, and testability of the
application code.
● Encapsulation: Each module encapsulates its components, ensuring that
they do not interfere with components defined in other modules. This
encapsulation helps in preventing naming conflicts and promoting
separation of concerns.
● Configuration Blocks: Modules can have configuration blocks that are
executed during the application's bootstrap phase. Configuration blocks
are used to set up the initial state of the application, configure services,
and perform other initialization tasks.
● Reusable and Composable: Modules can be reused across multiple
applications or combined to create larger, more complex applications. This
makes it easy to build modular, maintainable, and scalable AngularJS
applications by breaking them down into smaller, reusable pieces.
To define a module in AngularJS, you use the angular.module() function. Here's
an example of how to define a module named myApp:
// Define a module named 'myApp'
var myApp = angular.module('myApp', []);
In this example, angular.module('myApp', []) creates a new module named
myApp with an empty array [] as the list of dependencies. You can then add
controllers, services, directives, and other components to this module using the
module's methods, such as controller(), service(), directive(), etc.

2.3 Create and Start Component,

To create and start a component in an AngularJS application, you'll typically


follow these steps:

1. Define the Component: First, define the component by creating a new


AngularJS module and registering the component with the module. This
involves defining the component's template, controller, and any other
necessary configuration.
2. Use the Component in HTML: Once the component is defined, you can
use it in HTML by referencing its name as a custom HTML element or
attribute.
3. Start the Application: Finally, start the AngularJS application by
bootstrapping the main module.
4. Here's a step-by-step example of how to create and start a simple
component in an AngularJS application:

Here's a step-by-step example of how to create and start a simple component in


an AngularJS application:

1. Define the Component:

// Define a new AngularJS module named 'myApp'


var myApp = angular.module('myApp', []);

// Define a new component named 'helloWorld'

myApp.component('helloWorld', {

// Define the template for the component

template: '<h1>Hello, {{ $ctrl.name }}!</h1>',

// Define the controller for the component

controller: function() {

// Initialize the 'name' property

this.name = 'World';

});

In this example, we define a new AngularJS module named myApp and


register a component named helloWorld with the module. The component
has a template that displays a greeting message, and a controller that
initializes the name property.

2. Use the Component in HTML:

<!-- Use the 'hello-world' component in HTML -->

<hello-world></hello-world>

You can use the hello-world component in HTML like any other custom HTML
element. When the application runs, AngularJS will replace this element with the
template defined in the component.

3. Start the Application:

<!DOCTYPE html>

<html lang="en" ng-app="myApp">


<head>

<meta charset="UTF-8">

<title>AngularJS Component Example</title>

<!-- Include AngularJS library -->

<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script
>

</head>

<body>

<!-- Use the component in HTML -->

<hello-world></hello-world>

<!-- Bootstrap the application by manually starting the AngularJS module -->

<script>

angular.bootstrap(document, ['myApp']);

</script>

</body>

</html>

In this HTML file, we include the AngularJS library and define an HTML element
(<hello-world>) that uses the helloWorld component. Finally, we manually
bootstrap the AngularJS application by calling angular.bootstrap() and passing in
the name of the main module (myApp).

With these steps, you've created and started a simple component in an


AngularJS application. The component displays a greeting message ("Hello,
World!") using the template and controller defined in the component.
2.4 Why Components are important.

Components are the most basic UI building block of an Angular app. An Angular app
contains a tree of Angular components.

Angular components are a subset of directives, always associated with a template.


Unlike other directives, only one component can be instantiated for a given element in a
template.

A component must belong to an NgModule in order for it to be available to another


component or application. To make it a member of an NgModule, list it in the
declarations field of the NgModule metadata.

Note that, in addition to these options for configuring a directive, you can control a
component's runtime behavior by implementing life-cycle hooks. For more information,
see the Lifecycle Hooks guide.

Further information is available in the Usage Notes...

2.5 How we create a component,

Creating a component in Angular involves several steps, including defining the


component class, template, and metadata, and registering the component with an
Angular module. Here's a step-by-step guide on how to create a component in Angular:

1. Create a new Component File: Begin by creating a new file for your component.
Conventionally, Angular components are stored in separate files with a .ts
extension.

// hello.component.ts

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

@Component({

selector: 'app-hello',

templateUrl: './hello.component.html',

styleUrls: ['./hello.component.css']

})
export class HelloComponent {

message: string = 'Hello, Angular!';

2. Define the Component Class: In the component file, define a TypeScript class for
your component. This class will contain the logic and properties of the
component.

// hello.component.ts

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

@Component({

selector: 'app-hello',

templateUrl: './hello.component.html',

styleUrls: ['./hello.component.css']

})

export class HelloComponent {

message: string = 'Hello, Angular!';

3. Add Component Metadata: Decorate the component class with the @Component
decorator to provide metadata about the component. This metadata includes the
component's selector, template URL, style URLs, and other configuration options.

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

@Component({

selector: 'app-hello',

templateUrl: './hello.component.html',
styleUrls: ['./hello.component.css']

})

export class HelloComponent {

message: string = 'Hello, Angular!';

4. Create the Component Template: Create an HTML file for the component's
template. This file will define the structure and layout of the component's view.

<!-- hello.component.html -->

<div>

<h1>{{ message }}</h1>

</div>

5. (Optional) Define Component Styles: If necessary, create a CSS file to define


styles for the component. This file will contain the component-specific styles that
apply only to the component's template.

/* hello.component.css */

div {

text-align: center;

margin-top: 20px;

h1 {

color: blue;

6. Register the Component with a Module: Finally, register the component with an
Angular module by adding it to the declarations array of the module's metadata.
// app.module.ts

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

import { BrowserModule } from '@angular/platform-browser';

import { HelloComponent } from './hello.component';

@NgModule({

declarations: [

HelloComponent

],

imports: [

BrowserModule

],

bootstrap: [HelloComponent]

})

export class AppModule { }

7. Use the Component in HTML: Once the component is created and registered
with a module, you can use it in HTML templates by using its selector.

<!-- app.component.html -->

<app-hello></app-hello>

With these steps, you've successfully created a component in Angular. The component
can now be used in other components or templates within your Angular application.

2.6 Create Component using CLI

Creating components using the Angular CLI (Command Line Interface) is


straightforward and highly efficient. Here’s how you can do it:
1. Open the Terminal: Open your terminal or command prompt on your
computer.
2. Navigate to the Project Directory: Use the cd command to navigate to the
directory where you want to create the new component. For example, if your
Angular project is located in a folder named "my-angular-app," you would
run:

cd my-angular-app
3. Generate the Component: Use the Angular CLI’s generate or g command, followed
by component or its shorthand c, to create the new component. The basic syntax is as
follows:

ng generate component component-name


Replace component-name with the desired name for your new component. For
example, if you want to create a component named "my-component," you would run:

ng generate component my-component


4. Component Files Generated: The Angular CLI will create a new folder for your
component inside the src/app directory. It will generate several files for the component,
including:
component-name.component.ts: The TypeScript code for your component.
component-name.component.html: The HTML template for your component.
component-name.component.css (optional): A CSS file for component-specific styles.
component-name.component.spec.ts: A test file for testing your component.
5. Component Registration (Optional): In most cases, the Angular CLI will automatically
register the component in the app.module.ts file. If it doesn't, you may need to manually
add the component to the declarations array in the @NgModule decorator.
6. Use the Component: Now that your component is created, you can use it in other
components or templates by adding its selector (defined in the component class) to the
desired location.
That’s it! You have successfully created a new component using the Angular CLI, and
it’s ready to be used in your Angular application. The Angular CLI helps speed up the
development process by automatically generating the necessary files and boilerplate
code for your components.

2.7 What is nesting Component,

A nested component in React is a component that is related to an another component.


You can also consider it as a child component inside a parent component; but they are
not linked together using the inheritance concept but with the composition concept.
Therefore, all the components are nested together in order to create a bigger
component rather than a smaller component inheriting from the parent component.

The React component is a building block of a React application. A React component is


made up of the multiple individual components. React allows multiple components to be
combined to create larger components. Also, React components can be nested to any
arbitrary level.

Nested components will make your code more efficient and structured. However, if the
components are not nested or assembled properly, there is chance your code can
become more complex resulting in lower efficiency.

2.8 What is Component Template

A "Component Template" typically refers to a standardized blueprint or structure used to


create components in software development, particularly in the context of
component-based architectures such as those found in front-end web development
frameworks like Angular or React.

In the context of Angular, a Component Template refers to the HTML markup that
defines the structure of a component. This template describes how the component
should render its UI elements and how they should interact with the underlying logic of
the component.

In React, a Component Template could refer to JSX (JavaScript XML) code, which
similarly defines the structure of a component's UI.

In both cases, component templates help developers maintain consistency, improve


reusability, and manage the complexity of large-scale applications by separating
concerns between the UI presentation and the logic that drives it.

Component Templates play a crucial role in modern web development, particularly in


frameworks like Angular, React, and Vue.js. Here's a bit more detail on how they
function in these frameworks:

Angular:

● In Angular, a Component Template is typically defined using Angular's templating


syntax, which extends HTML with additional features like data binding, directives,
and template expressions.
● Angular components consist of three main parts: the component class, the
component template (HTML markup), and the component-specific styles.
● The template defines the structure of the component's view, including HTML
elements, Angular directives (like ngFor and ngIf), data bindings (using curly
braces {{}} or square brackets []), event bindings (using parentheses ()), and
more.
● Angular components encapsulate both the UI and the logic related to that UI,
making it easier to manage and reuse code across different parts of an
application.

2.9 Component Styles and Selectors.

Angular applications are styled with standard CSS. That means you can apply
everything you know about CSS stylesheets, selectors, rules, and media queries
directly to Angular applications.

Additionally, Angular can bundle component styles with components, enabling a more
modular design than regular stylesheets.

This page describes how to load and apply these component styles.

Run the live example / download example in Stackblitz and download the code from
there.

Using component styles

For every Angular component you write, you can define not only an HTML template, but
also the CSS styles that go with that template, specifying any selectors, rules, and
media queries that you need.

One way to do this is to set the styles property in the component metadata. The styles
property takes an array of strings that contain CSS code. Usually you give it one string,
as in the following example:

@Component({

selector: 'app-root',

template: `

<h1>Tour of Heroes</h1>

<app-hero-main [hero]="hero"></app-hero-main>

`,

styles: ['h1 { font-weight: normal; }']

})
export class HeroAppComponent {

/* . . . */

2.10 What is Data Binding? Splitting Application into Component,

Data binding is a fundamental concept in modern web development, particularly in


frameworks like Angular, React, and Vue.js. It refers to the synchronization of data
between the model (or business logic) of an application and the view (the UI
components that the user interacts with). There are typically two types of data binding:
one-way binding and two-way binding.

1. One-way Data Binding:


● One-way data binding involves binding data from the component's model (or
state) to the view. Changes in the model are reflected in the view, but changes in
the view do not affect the model.
● This type of data binding is commonly used when you want to display data from a
source (such as a database or an API) in the UI.
● Examples of one-way data binding include Angular's interpolation ({{}}), React's
props, and Vue.js's data properties.
2. Two-way Data Binding:
● Two-way data binding allows data to flow both from the model to the view and
from the view to the model. Changes in either the model or the view are
automatically propagated to the other.
● This type of data binding is useful for creating interactive user interfaces, such as
forms, where changes made by the user should immediately update the
underlying data and vice versa.
● Angular provides two-way data binding through ngModel, React typically handles
two-way binding through controlled components, and Vue.js offers the v-model
directive.
● Regarding splitting an application into components, this is a practice commonly
followed in component-based frameworks to manage the complexity of
large-scale applications. Here's how it works:
3. Component-based Architecture:
● Component-based architecture involves breaking down the user interface into
smaller, reusable building blocks called components.
● Each component encapsulates its own UI, behavior, and data, making it easier to
understand, maintain, and reuse.
● Components can be composed of other components, allowing developers to
create complex UIs by combining simple, self-contained parts.
● Examples of components might include a navigation bar, a sidebar, a user profile
card, a form input field, etc.
4. Advantages:

● Improved modularity: Components can be developed, tested, and maintained


independently, making it easier to scale and evolve the application.
● Reusability: Components can be reused across different parts of the application
or even in different projects, reducing development time and effort.
● Separation of concerns: Components separate the UI logic from the business
logic, promoting code organization and maintainability.
● Collaboration: Components enable teams to work on different parts of the
application simultaneously without interfering with each other's code.

2.11 String Interpolation

String interpolation in Angular is a feature that allows you to embed expressions within
double curly braces ({{}}) directly in the HTML template of a component. These
expressions are evaluated and the result is rendered as text in the HTML output. Here's
how string interpolation works in Angular:

1. Basic Syntax:
● You can use string interpolation to display component properties, execute
functions, or perform simple calculations directly in the HTML template.
● To use string interpolation, enclose the expression you want to evaluate within
double curly braces ({{}}).
● For example, if you have a component property named "name", you can display
its value in the template using string interpolation like this: {{ name }}.

2. Accessing Component Properties:
● String interpolation allows you to access properties defined in the component
class and display their values in the template.
● For example, if your component class has a property named "message", you can
display its value in the template using {{ message }}.

3. Executing Component Methods:
● String interpolation also enables you to execute methods defined in the
component class and display their return values in the template.
● For example, if your component class has a method named "formatName()" that
returns a formatted name, you can call this method within string interpolation like
this: {{ formatName() }}.

4. Expression Evaluation:
● Angular evaluates the expressions within the double curly braces and replaces
them with their corresponding values in the rendered HTML.
● If the expression returns a falsy value (such as false, null, undefined, 0, or an
empty string), Angular does not render anything for that expression.
5. Usage in HTML Attributes:
● String interpolation can be used not only to display text content but also to set
attribute values dynamically.
● For example, you can use string interpolation to dynamically set the value of an
input element's placeholder attribute like this: <input type="text" placeholder="{{
placeholderText }}">.
● String interpolation is a convenient and powerful feature in Angular that makes it
easy to work with data and logic in your component templates, allowing for
dynamic and interactive user interfaces.

,2.12 What is Property Binding,

Property Binding is a one-way data-binding technique. In property binding,


we bind a property of a DOM element to a field which is a defined property in
our component TypeScript code. Actually, Angular internally converts string
interpolation into property binding.
In this, we bind the property of a defined element to an HTML DOM element.
Syntax:
<element [property]= 'typescript_property'>

Approach:

● Define a property element in the app.component.ts file.


● In the app.component.html file, set the property of the HTML element
by assigning the property value to the app.component.ts file’s
element.

Example 1: setting value of an input element using property binding.


App.component.html
<input style = "color:green;
margin-top: 40px;
margin-left: 100px;"
[value]='title'>
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'GeeksforGeeks';
}

2.13 Difference between Property Binding and String Interpolation,

Property binding and string interpolation are both ways to dynamically manipulate
data in Angular templates, but they differ in syntax and use cases:

1. Syntax:
● Property Binding: In property binding, you use square brackets ([]) to bind
a component's property to an HTML element property, attribute, or
directive. For example:

<img [src]="imageUrl">

String Interpolation: In string interpolation, you enclose expressions within double


curly braces ({{}}) directly in the HTML template. For example:

<p>Welcome, {{ username }}!</p>

2. Evaluation:
● Property Binding: Property binding allows you to set properties of HTML
elements, directives, or component inputs based on data from the
component class. It evaluates the expression and sets the property
accordingly.
● String Interpolation: String interpolation evaluates expressions and directly
replaces them with their values in the rendered HTML content. It's primarily
used for displaying dynamic text content in the template.
3. Use Cases:
● Property Binding: Property binding is commonly used to bind properties of
HTML elements, directives, or component inputs to data from the
component class. It's ideal for scenarios where you want to dynamically
control the behavior or appearance of elements based on component data.
● String Interpolation: String interpolation is typically used to display dynamic
text content in the template. It's useful for scenarios where you want to
display the value of a component property or the result of an expression
directly within the HTML markup.
4. Compatibility:
● Property Binding: Property binding is used when you want to bind data to
HTML attributes, properties, or directive inputs. It's essential for setting
dynamic values that cannot be achieved with plain HTML attributes.
● String Interpolation: String interpolation is more limited in scope compared
to property binding. It's mainly used for displaying dynamic text content
and cannot be used to set attributes or properties of HTML elements or
directives

2.14What are Binding Properties and Events,

In Angular, binding properties and events are fundamental concepts that enable
communication between components and their templates, allowing for dynamic
interactions and data flow within an application.

Binding Properties:

● Binding properties, also known as property binding, enable you to set


properties of HTML elements, Angular directives, or custom components
dynamically based on data from the component class.
● Property binding uses square brackets ([]) syntax in the template to bind a
component's property to an HTML element property, directive input, or
custom component input.
● For example, you can bind the value of an input element to a component
property like this:

<input [value]="username">
● This sets the value property of the input element to the value of the
username property in the component class. Any changes to the username
property will be reflected in the input element.

Binding Events:

● Binding events, also known as event binding, allow you to listen for and
respond to user actions or events triggered by HTML elements or custom
components.
● Event binding uses parentheses (()) syntax in the template to bind an
event handler method from the component class to an event emitted by an
HTML element or component.
● For example, you can bind the click event of a button to a method named
onClick() in the component class like this:

<button (click)="onClick()">Click Me</button>

● When the button is clicked, the onClick() method in the component class is
invoked, allowing you to handle the event and perform any necessary
actions.

2.15 Two Way binding,


Two-way binding is a powerful feature in Angular that allows for automatic
synchronization of data between the component class and the template in both
directions. It combines property binding and event binding into a single
convenient syntax, enabling seamless communication between the view and the
model.

In Angular, two-way binding is achieved using the ngModel directive, which


provides a convenient way to bind the value of an input element to a component
property and listen for changes to that property.

Here's how two-way binding works:

1. Binding Syntax:
● Two-way binding is denoted by the ngModel directive, which is typically
applied to input, select, and textarea elements.
● It uses the banana-in-a-box syntax [(ngModel)] to represent two-way data
binding.
● For example, you can bind the value of an input element to a component
property named username like this:
<input [(ngModel)]="username">

● This binds the value of the input element to the username property in the
component class. Any changes made to the input field will automatically
update the username property, and vice versa.

2. Event Binding:
● Under the hood, two-way binding combines property binding and event
binding.
● The ngModel directive binds the value of the input element to the
component property using property binding ([ngModel]="username").
● It also listens for changes to the input element's value and updates the
component property using event binding
((ngModelChange)="username=$event").

3. Form Control:
● Two-way binding is commonly used in forms to bind input elements to
properties representing form values.
● By using ngModel within a form, you can easily bind form controls to
component properties and handle form submissions with ease.
● Angular also provides features like form validation and control states to
enhance the functionality of forms with two-way binding.

Two-way binding simplifies the process of keeping the view and the model in
sync, reducing boilerplate code and enhancing the developer experience.
However, it's important to use two-way binding judiciously, especially in larger
applications, to avoid complexity and potential performance issues.

2.16 Combine Forms with Data binding.

Combining forms with data binding is a powerful technique in Angular for creating
dynamic and interactive user interfaces. Angular provides robust support for
building forms using both template-driven forms and reactive forms, and these
forms can be seamlessly integrated with data binding to enable bidirectional data
flow between the form controls and the component class.

Here's how you can combine forms with data binding in Angular:
1. Template-Driven Forms:
● Template-driven forms rely on directives such as ngModel for two-way data
binding to bind form controls directly to properties in the component class.
● You can use string interpolation or property binding to display the initial
values of form fields from component properties, and changes to the form
controls are automatically reflected in the corresponding component
properties.

For example, to bind an input field to a component property and display its initial
value, you can use:

<input type="text" [(ngModel)]="username">

Here, changes to the input field update the username property in the component
class, and changes to the username property update the input field.

2. Reactive Forms:
● Reactive forms use a more programmatic approach where form controls
and their values are managed explicitly in the component class using
FormControl, FormGroup, and FormArray classes from the
@angular/forms module.
● With reactive forms, you can use data binding to initialize form controls
with values from the component class and keep them synchronized.

For example, to initialize a FormControl with a value from a component property,


you can do:

// In the component class

username = 'JohnDoe';

profileForm = new FormGroup({

username: new FormControl(this.username)

});

In the template, you can bind the FormControl's value to the corresponding input
field using property binding:=

<input type="text" [formControl]="profileForm.get('username')">

3. Validation and Error Handling:


● Both template-driven and reactive forms support validation using Angular's
built-in validators or custom validators.
● You can bind form validation errors to the template using property bindings
and display error messages dynamically based on form state.

For example, you can use the errors property of a FormControl to display
validation errors in the template:

<div *ngIf="profileForm.get('username').errors?.required">Username is
required</div>

By combining forms with data binding in Angular, you can create forms that are
not only dynamic and interactive but also seamlessly integrated with the
component class, allowing for efficient management of form data and state.

******************************************************************************************
UNIT –III: Dependency Injection Angular JS

[06L] Max Marks: 10

3.1 What is Dependency Injection,

Dependency injection (DI) is the part of the Angular framework that provides
components with access to services and other resources. Angular provides the
ability for you to inject a service into a component to give that component access
to the service.Add the @Injectable() decorator to a service class so that Angular
can inject it into a component as a dependency; the optional argument tells
Angular where to register this class by default.

@Injectable({providedIn: 'root'})

export class HeroService {

Something injectable must be registered with an injector before it can be created


and used.

● Register an injectable with a provider, an object that tells an injector how to


obtain or create a dependency. For a service class, the provider is typically
the class itself.
● You don't have to create injectors. Under the hood Angular creates an
application-wide root injector for you during the bootstrap process. It
creates additional child injectors as needed.
● An injectable dependency doesn't have to be a class — it could be a
function, for example, or a value.

When Angular creates a new instance of a component class, it determines which


services or other dependencies that component needs by looking at the
constructor parameter types. For example, the constructor of
HeroListComponent needs HeroService.

src/app/hero-list.component.ts (constructor)

constructor(private service: HeroService) { }

When Angular discovers that a component depends on a service, it first checks if


the injector has any existing instances of that service. If a requested service
instance doesn't yet exist, the injector makes one using the registered provider
and adds it to the injector before returning the service to Angular.
When all requested services have been resolved and returned, Angular can call
the component's constructor with those services as arguments.

The process of HeroService injection looks something like this.

Service

Providing services

You must register at least one provider of any service you are going to use. The
provider can be part of the service's own metadata, making that service available
everywhere, or you can register providers with specific components. You register
providers in the metadata of the service (in the @Injectable() decorator) or
@Component() metadata

By default, the Angular CLI command ng generate service registers a provider


with the root injector for your service by including provider metadata in the
@Injectable() decorator. The tutorial uses this method to register the provider of
HeroService class definition.

hero.service.ts (provide in root)

@Injectable({providedIn: 'root'})

export class HeroService {

When you provide the service at the root level, Angular creates a single, shared
instance of HeroService and injects it into any class that asks for it. Registering
the provider in the @Injectable() metadata also allows Angular to optimize an
app by removing the service from the compiled application if it isn't used, a
process known as tree-shaking.
When you register a provider at the component level, you get a new instance of
the service with each new instance of that component. At the component level,
register a service provider in the providers property of the @Component()
metadata.

src/app/hero-list.component.ts (component providers)

@Component({

standalone: true,

selector: 'app-hero-list',

templateUrl: './hero-list.component.html',

imports: [ NgFor, NgIf, HeroDetailComponent ],

providers: [ HeroService ]

})

3.2 What is Services,

In AngularJS, a service is a function, or object, that is available for, and limited to, your
AngularJS application.

AngularJS has about 30 built-in services. One of them is the $location service.

The $location service has methods which return information about the location of the
current web page:

Example

Use the $location service in a controller:

var app = angular.module('myApp', []);

app.controller('customersCtrl', function($scope, $location) {


$scope.myUrl = $location.absUrl();

});

Why use Services?


For many services, like the $location service, it seems like you could use objects that are
already in the DOM, like the window.location object, and you could, but it would have some
limitations, at least for your AngularJS application.

AngularJS constantly supervises your application, and for it to handle changes and events
properly, AngularJS prefers that you use the $location service instead of the
window.location object.

3.3 Logging Service and Injection,

Service is a broad category encompassing any value, function, or feature that an app
needs. A service is typically a class with a narrow, well-defined purpose. It should do
something specific and do it well.

Angular distinguishes components from services to increase modularity and reusability.


By separating a component's view-related functionality from other kinds of processing,
you can make your component classes lean and efficient.

Ideally, a component's job is to enable the user experience and nothing more. A
component should present properties and methods for data binding, in order to mediate
between the view (rendered by the template) and the application logic (which often
includes some notion of a model).

A component can delegate certain tasks to services, such as fetching data from the
server, validating user input, or logging directly to the console. By defining such
processing tasks in an injectable service class, you make those tasks available to any
component. You can also make your app more adaptable by injecting different providers
of the same kind of service, as appropriate in different circumstances.

Angular doesn't enforce these principles. Angular does help you follow these principles
by making it easy to factor your application logic into services and make those services
available to components through dependency injection.

Service examples

Here's an example of a service class that logs to the browser console.


src/app/logger.service.ts (class)

export class Logger {

log(msg: any) { console.log(msg); }

error(msg: any) { console.error(msg); }

warn(msg: any) { console.warn(msg); }

3.4 Create Data Service,

1.Generate a new service:

Open your terminal and navigate to your Angular project directory. Then, use the
Angular CLI to generate a new service. You can do this by running the following
command:

ng generate service data

This command will create a new service file named data.service.ts and a corresponding
unit test file.

2. Implement the service:

Open the data.service.ts file in your code editor, and you'll see a basic service class
already generated for you. You can modify it to suit your needs. Here's an example of a
simple data service that provides methods for managing a list of items:

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

@Injectable({

providedIn: 'root'

})

export class DataService {

private items: string[] = [];

constructor() { }
// Method to get all items

getItems(): string[] {

return this.items;

// Method to add an item

addItem(item: string): void {

this.items.push(item);

// Method to clear all items

clearItems(): void {

this.items = [];

In this example, the DataService class has methods for getting all items, adding an
item, and clearing all items from the list.

3. Inject the service into components:

You can now inject the DataService into any Angular component where you want to use
it. For example, in a component's constructor:

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

import { DataService } from './data.service';

@Component({

selector: 'app-example',

template: `

<ul>
<li *ngFor="let item of items">{{ item }}</li>

</ul>

})

export class ExampleComponent {

items: string[];

constructor(private dataService: DataService) {

this.items = this.dataService.getItems();

In this example, the ExampleComponent injects the DataService into its constructor and
uses it to get the list of items.

4. Use the service in your application:

You can now use the service methods wherever you need to manage data in your
Angular application. For example, you can use it to display a list of items in a
component's template, add new items, or clear the list.

That's it! You've created a basic data service in Angular that can be used to manage
data across your application. Feel free to extend and customize the service according to
your application's requirements.

3.5 Instance of Services,

What is instance?
In JavaScript instance simply mean a new child has been born with same DNA as their
parent, and same DNA mean they have all their parents attributes.
So here(In JS world) Parent is Class which is, in our case it is service!

What is service?
Service is just another class which have been decorated with @Injectable()
When mark a class with this decorator we actually telling Angular to consider this class
as injectable objects which can be used and injected into other classes.
Take this code as an example
@Injectable()

class MyService {}

@Component()

class MyComponent {

constructor(private service: MyService) {}

If we run our app this way, we will face error with title Null Injector which is saying
that service is not provided any where so it is not usable!
That simply mean, this service does not have any instance available for our component
to be used!

3.6 Insert Service into Services,

To inject one service into another service in Angular, you can use constructor injection.
Here's how you can insert one service into another service:

1.Service to be Injected:

First, let's assume you have a service called ServiceA that you want to inject into
another service.

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

@Injectable({

providedIn: 'root'

})

export class ServiceA {

constructor() { }

// Methods and properties of ServiceA

2. Service to Inject the Other Service:


Now, let's create a service called ServiceB where we want to inject ServiceA.

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

import { ServiceA } from './service-a'; // Import the service to be injected

@Injectable({

providedIn: 'root'

})

export class ServiceB {

constructor(private serviceA: ServiceA) {

// ServiceA is injected into ServiceB through constructor injection

// Methods and properties of ServiceB

Here, ServiceB injects ServiceA via its constructor. Angular's dependency injection
system takes care of providing an instance of ServiceA to ServiceB when it's
instantiated.

3. Usage:

You can now use methods and properties of ServiceA within ServiceB as needed.

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

import { ServiceA } from './service-a';

@Injectable({

providedIn: 'root'

})

export class ServiceB {

constructor(private serviceA: ServiceA) {


this.serviceA.someMethod(); // Example of using ServiceA method in ServiceB

// Methods and properties of ServiceB

By injecting one service into another, you can modularize your code and promote
reusability and maintainability. It also allows you to decouple different parts of your
application and manage dependencies more efficiently. Remember to import the service
you want to inject and declare it as a constructor parameter in the service where you
want to use it.

3.7 How to use service in Cross Component,

Using a service across multiple components in Angular involves injecting the service
into each component that needs to access its functionality. This is achieved through
Angular's dependency injection system.Here's a step-by-step guide on how to use a
service across multiple components:

1. Create the Service:

First, you need to create a service that contains the functionality or data you want to
share across components. This service should be decorated with @Injectable() and
typically provided at the root level.

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

@Injectable({

providedIn: 'root'

})

export class DataService {

sharedData: string;

constructor() { }

setData(data: string): void {

this.sharedData = data;

}
getData(): string {

return this.sharedData;

2. Inject the Service into Components:

Next, you need to inject the service into the components where you want to use it. This
is done by adding the service as a constructor parameter in the component class.

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

import { DataService } from './data.service';

@Component({

selector: 'app-component-a',

template: `

<h1>Component A</h1>

<button (click)="setData()">Set Data</button>

})

export class ComponentA {

constructor(private dataService: DataService) { }

setData(): void {

this.dataService.setData('Data from Component A');

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

import { DataService } from './data.service';

@Component({
selector: 'app-component-b',

template: `

<h1>Component B</h1>

<p>Data from DataService: {{ getData() }}</p>

})

export class ComponentB {

constructor(private dataService: DataService) { }

getData(): string {

return this.dataService.getData();

3. Use the Service in the Components:

Once the service is injected into the components, you can access its methods and
properties within the component's methods or templates.

4. Ensure the Service is Provided at the Root Level:

Make sure that the service is provided at the root level (providedIn: 'root') or in a module
where the components are declared. This ensures that Angular creates a single
instance of the service that is shared across all components.

By following these steps, you can use a service across multiple components in Angular,
allowing them to share data and functionality efficiently.

3.8 What is Hierarchical Injector. What is Routing? Loading of Routes,

n Angular, a Hierarchical Injector is a concept related to dependency injection where


each Angular application has its own hierarchical injector. This injector is responsible for
managing the instantiation and resolution of services and other injectable objects within
the Angular application.
Here's what you need to know about the Hierarchical Injector:

1. Hierarchy:
● Angular applications have a hierarchical structure, with components nested
within one another to create a tree-like structure.
● Each component in the hierarchy has its own injector, which is a child injector of
its parent component's injector.
● This creates a hierarchy of injectors that mirrors the component tree structure.

2. Scope:
● Each injector in the hierarchy has its own scope, meaning that services
registered with a particular injector are available within that injector's subtree of
components.
● Services registered with a parent injector are available to all child injectors and
their components, but not vice versa.
● This allows for encapsulation and scoping of services to specific parts of the
application.

3.Lazy Loading:

● Angular's Hierarchical Injector plays a crucial role in lazy loading modules and
routes.
● When a module or route is lazy loaded, Angular creates a child injector for the
lazy-loaded module or route.
● This child injector inherits services from its parent injector but also has its own
set of providers specific to the lazy-loaded module or route.
● Lazy loading helps improve the initial loading time of the application by loading
only the necessary modules and components when they are requested.

Regarding Routing:

Routing in Angular refers to the process of navigating between different views or


components in an Angular application. Angular's built-in router allows developers to
define navigation paths and associate them with specific components, enabling users to
navigate seamlessly within the application.

Here's how routing works in Angular:

1. Route Configuration:
● Routes in Angular are defined using the RouterModule.forRoot() method in the
root module (AppModule) and the RouterModule.forChild() method in feature
modules.
● Routes are configured using an array of route objects, where each route object
specifies a path and the component to be displayed when that path is matched.

2.Router Outlet:

● In the application's HTML template, a special directive called


<router-outlet></router-outlet> is used to mark the location where the routed
component should be displayed.
● When a user navigates to a specific route, Angular replaces the content of the
router outlet with the component associated with that route.

3.Router Navigation:

● Navigation in Angular can be triggered programmatically using the Router


service, which provides methods for navigating to specific routes, navigating
back and forward in the browser history, and more.
● Navigation can also be triggered by user interaction, such as clicking on links or
buttons with routerLink directives.

4.Route Parameters:

● Angular's router supports route parameters, which allow dynamic values to be


passed as part of the URL path.
● Route parameters are specified in the route path using the colon (:) syntax, and
their values can be accessed within the routed component using the
ActivatedRoute service.

Regarding Loading of Routes:

1. Eager Loading:
● By default, Angular eagerly loads all routes defined in the application's route
configuration when the application starts.
● This means that all components associated with the routes are loaded and
initialized upfront, increasing the initial loading time of the application.
2. Lazy Loading:
● To improve the initial loading time of the application, Angular supports lazy
loading of routes, where modules and components are loaded on-demand as
they are requested by the user.
● Lazy loading is achieved by configuring routes with loadChildren property instead
of component property in the route configuration.
● When a lazy-loaded route is accessed, Angular dynamically loads the
corresponding module and component, creating a child injector for the
lazy-loaded module.
3.Preloading Strategies:

● Angular provides preloading strategies that allow developers to preload certain


lazy-loaded modules in the background while the user interacts with the
application.
● Preloading strategies help strike a balance between reducing the initial loading
time and ensuring that essential parts of the application are readily available to
the user.

In summary, Angular's Hierarchical Injector manages the instantiation and scoping of


services within the application's component hierarchy, while routing allows for navigation
between different views or components. Lazy loading of routes, facilitated by Angular's
router and injector, helps improve the initial loading time of the application by loading
modules and components on-demand.

3.9 Navigation and it path,

Navigation and IT paths can intertwine in various ways, especially in the realm of digital
navigation systems and applications. Here's a breakdown of how these two domains
intersect:

1. GPS Technology: Information Technology plays a crucial role in the development


and implementation of GPS (Global Positioning System) technology. GPS relies
on a network of satellites, ground stations, and sophisticated software algorithms
to provide accurate location information to users. IT professionals are involved in
developing GPS software, managing satellite networks, and creating
user-friendly navigation interfaces.
2. Navigation Software: IT professionals are responsible for designing, developing,
and maintaining navigation software used in various applications such as vehicle
navigation systems, mobile mapping apps, and maritime navigation systems.
This software utilizes complex algorithms to calculate routes, provide real-time
traffic updates, and offer navigation guidance to users.
3. Geographic Information Systems (GIS): GIS technology combines geographic
data with IT tools to analyze, visualize, and interpret spatial information. GIS is
widely used in navigation applications for mapping, route planning, and spatial
analysis. IT professionals play a key role in developing GIS software, managing
spatial databases, and integrating GIS functionality into navigation systems.
4. Data Management and Processing: Navigation systems rely on vast amounts of
data, including maps, satellite imagery, traffic information, and user-generated
content. IT professionals are responsible for managing and processing this data
efficiently to ensure accurate and up-to-date navigation information for users.
5. User Interfaces and Experience: User-friendly interfaces are essential for
navigation applications to provide intuitive and seamless user experiences. IT
professionals work on designing and developing user interfaces that are easy to
navigate, visually appealing, and accessible across different devices and
platforms.
6. Integration with Other Technologies: Navigation systems often integrate with
other technologies such as IoT (Internet of Things), artificial intelligence, and
cloud computing to enhance functionality and provide advanced features such as
predictive navigation, personalized recommendations, and real-time
collaboration.

3.10 Styling of Router Links,

Styling the active router link in angular allows the user to differentiate between the
active router link and inactive router links. Angular provides a special mechanism to
work with active router links.

Approach:

Create the Angular app to be used.

Create the header component that contains the navigation links.

Then apply the “routerLinkActive” on each router link and provide the CSS class to this
property. Here we have created the “active” class in CSS file.

Provide the { exact : true } to the root route to avoid multiple active router links.

Syntax:

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

Example: We have created the header component with specified routes.

<span>

<ul>

<li><a routerLink="/" routerLinkActive="active">

Home

</a></li>

<li><a routerLink="/products"

routerLinkActive="active">Products

</a></li>

<li><a routerLink="/about"
routerLinkActive="active">About Us

</a></li>

<li><a routerLink="/contact"

routerLinkActive="active">Contact Us

</a></li>

</ul>

</span>

<router-outlet></router-outlet>

3.11 Relative Path Navigation,

Here we have provided the “routerLinkActive” which is routing functionality that


automatically activate the current route, and we have to provide the CSS class as well.
Here in routerLinkActive = “active” active is a CSS class that automatically applied to
the activated route.

.active{

background: 'white'

But here, it still causes an issue our Home route is always active even we navigate to
some other route the reason behind this is the way “routerLinkActive” works. The home
route works on “localhost:4200/” and other routes are “localhost:4200/about” so
“routerLinkActive” finds “localhost:4200/” inside every other route and the Home router
link is always active to deal with this angular provide another directive called
routerLinkActiveOptions.

Updated

<span>

<ul>

<li><a routerLink="/" routerLinkActive="active"

[routerLinkActiveOptions]={exact:true}>Home
</a></li>

<li><a routerLink="/products"

routerLinkActive="active">Products

</a></li>

<li><a routerLink="/about"

routerLinkActive="active">About Us

</a></li>

<li><a routerLink="/contact"

routerLinkActive="active">Contact Us

</a></li>

</ul>

</span>

<router-outlet></router-outlet>

So routerLinkActiveOptions allow only the exact path match as an active route for the
Home component.

Output:
3.12 De ne parameter in Routing,

In routing, a "parameter" refers to a dynamic segment of a URL that allows for passing
data between different parts of an application. These parameters are typically used to
identify specific resources or states within the application. In the context of web
development, parameters are commonly seen in the URLs of web pages.

In Angular routing, parameters are defined within route paths using placeholders. These
placeholders are prefixed with a colon (:) followed by a parameter name. For example,
consider the following route path definition:

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

In this example, :id is a route parameter. When navigating to a URL like /product/123,
the value 123 is passed as the value of the id parameter to the
ProductDetailComponent.

Parameters in routing serve several purposes:

● Dynamic Routing: Parameters enable dynamic routing by allowing parts of the


URL to be variable. This makes it possible to create routes that respond to
different inputs and display different content based on the provided parameters.
● Data Passing: Parameters provide a mechanism for passing data between
different components or views within an application. Components can access
route parameters to retrieve information needed for rendering or processing.
● State Management: Parameters can be used to represent the state of the
application within the URL. This allows users to bookmark or share URLs that
correspond to specific states or resources within the application.
● URL Segmentation: Parameters help in segmenting URLs into meaningful parts,
making them more human-readable and SEO-friendly.

3.13 Fetch Routing Parameter

To fetch routing parameters in an Angular application, you can use the ActivatedRoute
service provided by Angular's router module. Here's how you can fetch routing
parameters:

1. Import ActivatedRoute: First, import the ActivatedRoute service from the


'@angular/router' package in your component where you want to access the
routing parameters.

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

2. Inject ActivatedRoute: Next, inject the ActivatedRoute service into your


component's constructor.
constructor(private route: ActivatedRoute) { }

3. Access Routing Parameters: You can access routing parameters using the
snapshot or by subscribing to the params Observable provided by
ActivatedRoute.

ngOnInit(): void {

const id = this.route.snapshot.paramMap.get('id');

console.log(id); // Do whatever you need with the parameter value

b. Using Observable (Recommended if the parameter value might change without


leaving the component):

ngOnInit(): void {

this.route.params.subscribe(params => {

const id = params['id'];

console.log(id); // Do whatever you need with the parameter value

});

****************************************************************************************************
UNIT-IV: Forms in Angular JS

[08L] Max Marks: 15

4.1 What is Forms and how do we handle it? Reactive Approach,

Forms are a fundamental aspect of web development, enabling interaction between


users and web applications by capturing and processing user input. In Angular, forms
can be handled using two main approaches: Template-driven forms and Reactive forms.

Template-driven forms rely on directives and two-way data binding provided by


Angular's template syntax. With this approach, form logic is primarily defined in the
HTML template, making it suitable for simple forms with basic validation requirements.
Angular automatically tracks changes and updates the model and view accordingly.

Here's a basic example of a template-driven form in Angular:

<form #myForm="ngForm" (ngSubmit)="onSubmit()">

<input type="text" name="name" [(ngModel)]="user.name" required>

<input type="email" name="email" [(ngModel)]="user.email" required email>

<button type="submit">Submit</button>

</form>

In contrast, Reactive forms are built programmatically in the component class using
Angular's FormBuilder service and FormControl, FormGroup, and FormArray classes.
This approach offers more control and flexibility, making it suitable for complex forms
with dynamic requirements and extensive validation.

Here's a basic example of a reactive form in Angular:

import { FormBuilder, FormGroup, Validators } from '@angular/forms';

export class MyComponent {

myForm: FormGroup;

constructor(private fb: FormBuilder) {

this.myForm = this.fb.group({

name: ['', Validators.required],


email: ['', [Validators.required, Validators.email]]

});

onSubmit() {

if (this.myForm.valid) {

console.log(this.myForm.value);

<form [formGroup]="myForm" (ngSubmit)="onSubmit()">

<input type="text" formControlName="name">

<input type="email" formControlName="email">

<button type="submit">Submit</button>

</form>

In this reactive form example, the form structure and validation rules are defined in the
component class, providing more control and easier testing. Reactive forms are often
preferred for larger applications or forms with complex validation requirements.

Both approaches have their advantages and use cases, and the choice between them
depends on the specific requirements of your application. Angular's comprehensive
forms module provides robust support for building and handling forms, empowering
developers to create interactive and user-friendly web applications.

4.2 Template Driven,

Template-driven forms in Angular rely on directives and two-way data binding provided
by Angular's template syntax. This approach is characterized by defining the form
structure and behavior directly within the HTML template. Template-driven forms are
suitable for simpler forms with basic validation requirements and are generally easier to
set up and understand compared to reactive forms.
Here's how you can create a template-driven form in Angular:

1. Import FormsModule: Ensure you have the FormsModule imported in your


Angular module file (usually app.module.ts).

import { FormsModule } from '@angular/forms';

Add FormsModule to the imports array within the @NgModule decorator.

2. Create the Form in HTML Template: Define the form structure and bindings
directly in the HTML template using Angular's template syntax and directives
such as ngModel for two-way data binding and ngForm to create the form.

<form #myForm="ngForm" (ngSubmit)="onSubmit()">

<label for="name">Name:</label>

<input type="text" id="name" name="name" [(ngModel)]="user.name" required>

<label for="email">Email:</label>

<input type="email" id="email" name="email" [(ngModel)]="user.email" required email>

<button type="submit">Submit</button>

</form>

3. Handle Form Submission: Define a method in your component to handle form


submission. This method can be invoked when the form is submitted and can
perform actions like validating the form, sending form data to a server, or
updating the application state based on the form data.

export class MyComponent {

user = { name: '', email: '' };

onSubmit() {

if (myForm.form.valid) {

console.log(this.user);
// Perform other actions like sending data to server

4.3 Create Template Driven Forms,

You can recreate the sample application from the code provided here

1. The provided sample application creates the Hero class which defines the data
model reflected in the form.

src/app/hero.ts

export class Hero {

constructor(

public id: number,

public name: string,

public power: string,

public alterEgo?: string

){ }

2. The form layout and details are defined in the HeroFormComponent class.

src/app/hero-form/hero-form.component.ts (v1)

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

import { Hero } from '../hero';

@Component({

selector: 'app-hero-form',

templateUrl: './hero-form.component.html',
styleUrls: ['./hero-form.component.css']

})

export class HeroFormComponent {

powers = ['Really Smart', 'Super Flexible',

'Super Hot', 'Weather Changer'];

model = new Hero(18, 'Dr. IQ', this.powers[0], 'Chuck Overstreet');

submitted = false;

onSubmit() { this.submitted = true; }

The component's selector value of "app-hero-form" means you can drop this form in a
parent template using the <app-hero-form> tag.

3. The following code creates a new hero instance, so that the initial form can show
an example hero.

const myHero = new Hero(42, 'SkyDog',

'Fetch any object at any distance',

'Leslie Rollover');

console.log('My hero is called ' + myHero.name); // "My hero is called SkyDog"

This demo uses dummy data for model and powers. In a real app, you would inject a
data service to get and save real data, or expose these properties as inputs and
outputs.

4. The application enables the Forms feature and registers the created form
component.

src/app/app.module.ts

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

import { BrowserModule } from '@angular/platform-browser';

import { CommonModule } from '@angular/common';


import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';

import { HeroFormComponent } from './hero-form/hero-form.component';

@NgModule({

imports: [

BrowserModule,

CommonModule,

FormsModule

],

declarations: [

AppComponent,

HeroFormComponent

],

providers: [],

bootstrap: [ AppComponent ]

})

export class AppModule { }

5. The form is displayed in the application layout defined by the root component's
template.

src/app/app.component.html

\<app-hero-form></app-hero-form>

The initial template defines the layout for a form with two form groups and a submit
button. The form groups correspond to two properties of the Hero data model, name
and alterEgo. Each group has a label and a box for user input.
The Name <input> control element has the HTML5 required attribute

The Alter Ego <input> control element does not because alterEgo is optional

The Submit button has some classes on it for styling. At this point, the form layout is all
plain HTML5, with no bindings or directives.

6. The sample form uses some style classes from Twitter Bootstrap: container,
form-group, form-control, and btn. To use these styles, the application's style
sheet imports the library.

src/styles.css

@import url('https://unpkg.com/bootstrap@3.3.7/dist/css/bootstrap.min.css');

7. The form makes the hero applicant choose one superpower from a fixed list of
agency-approved powers. The predefined list of powers is part of the data model,
maintained internally in HeroFormComponent. The Angular NgForOf directive
iterates over the data values to populate the <select> element.

src/app/hero-form/hero-form.component.html (powers)

<div class="form-group">

<label for="power">Hero Power</label>

<select class="form-control" id="power" required>

<option *ngFor="let pow of powers" [value]="pow">{{pow}}</option>

</select>

</div>

If you run the application right now, you see the list of powers in the selection control.
The input elements are not yet bound to data values or events, so they are still blank
and have no behavior.

Early form with no binding


4.4 What is Registering Control,

Registering controls in Angular, especially when working with reactive forms, is crucial
for establishing a connection between the form controls defined in the component class
and the form elements in the HTML template. This registration process enables Angular
to track changes to form controls, manage their state, perform validation, and handle
user input effectively.

There are three main types of form controls in Angular: FormControl, FormGroup, and
FormArray.

Registering controls in Angular is a crucial step when working with reactive forms. It
involves creating instances of FormControl, FormGroup, or FormArray objects and
associating them with elements in the HTML template. This registration process allows
Angular to track changes to form controls and manage their state.

By registering controls in Angular, you enable seamless interaction between the


component class and the HTML template, allowing for dynamic forms with robust
functionality and validation.

4.5 Use and SubIT of Forms,4.6 Access of Forms,4.7How to add validation


in use input,4.8 Build-In Validation 4.9 HTML5 Validation,4.10 Output
Validation and Error Messages,

Handling forms in Angular involves various aspects such as form submission, accessing
form data, adding validation to user input, displaying error messages, and utilizing
built-in and HTML5 validation features. Let's break down each of these aspects:

1. Form Submission:
● In Angular, you can handle form submission by listening to the (ngSubmit) event
on the <form> element and executing a method in the component when the form
is submitted.
● Inside the component, you can access the form data using the value property of
the form instance.
2. Accessing Form Data:
● You can access form data using the value property of the form instance in the
component class.
● For reactive forms, you can access form data similarly but through the controls or
form groups defined in the component.

3. Adding Validation to User Input:


● Angular provides built-in validators such as required, min, max, pattern, etc.,
which can be added to form controls using directives or programmatically.
● You can also create custom validators to suit specific validation requirements.

4. Built-In Validation:
● Angular offers built-in validation directives like required, minLength, maxLength,
etc., which can be applied directly to form controls in the template.
● For example, <input type="text" [(ngModel)]="name" name="name" required>
applies the required validation to ensure that the input is not empty.

5. HTML5 Validation:
● HTML5 provides built-in validation attributes such as required, min, max, pattern,
etc., which can be added to form elements without Angular directives.
● For example, <input type="text" [(ngModel)]="name" name="name" required>
utilizes HTML5 validation for required input.

6. Output Validation and Error Messages:


● Angular provides various ways to display validation errors to users, such as using
Angular directives like ngIf and ngClass to conditionally show error messages
based on form control validity.
● You can also leverage Angular's FormGroup and FormControl APIs to
programmatically check for form control validity and display appropriate error
messages.
● Here's an example of how you might implement form validation and error
messages in Angular:

<form (ngSubmit)="onSubmit()" #myForm="ngForm">

<input type="text" [(ngModel)]="name" name="name" required>


<div *ngIf="myForm.controls['name'].invalid && (myForm.controls['name'].dirty ||
myForm.controls['name'].touched)">

<div *ngIf="myForm.controls['name'].errors.required">Name is required</div>

</div>

<button type="submit">Submit</button>

</form>

In this example, we're using Angular's built-in validation and error message handling to
ensure that the name field is required. If the field is empty and touched or dirty, it will
display the error message "Name is required".

4.11 Two Way Binding, Grouping,

Data binding in AngularJS is the synchronization between the model and the view.

When data in the model changes, the view reflects the change, and when data in the
view changes, the model is updated as well. This happens immediately and
automatically, which makes sure that the model and the view is updated at all times.

Example

<div ng-app="myApp" ng-controller="myCtrl">

Name: <input ng-model="firstname">

<h1>{{firstname}}</h1>

</div>

<script>

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {

$scope.firstname = "John";

$scope.lastname = "Doe";

});

</script>

4.12 Radio Button Handling,


The radio-button label is provided as the content to the <mat-radio-button> element.
The label can be positioned before or after the radio-button by setting the labelPosition
property to 'before' or 'after'.

If you don't want the label to appear next to the radio-button, you can use aria-label or
aria-labelledby to specify an appropriate label.

Radio groups

Radio-buttons should typically be placed inside of an <mat-radio-group> unless the


DOM structure would make that impossible (e.g., radio-buttons inside of table cells).
The radio-group has a value property that reflects the currently selected radio-button
inside of the group.

Individual radio-buttons inside of a radio-group will inherit the name of the group.

Use with @angular/forms

<mat-radio-group> is compatible with @angular/forms and supports both FormsModule


and ReactiveFormsModule.

Default Color Configuration

The default color for radio buttons can be configured globally using the
MAT_RADIO_DEFAULT_OPTIONS provider

providers: [{

provide: MAT_RADIO_DEFAULT_OPTIONS,

useValue: { color: 'accent' },

}]

Accessibility

MatRadioButton uses an internal <input type="radio"> to provide an accessible


experience. This internal radio button receives focus and is automatically labelled by the
text content of the <mat-radio-button> element. Avoid adding other interactive controls
into the content of <mat-radio-button>, as this degrades the experience for users of
assistive technology.
Always provide an accessible label via aria-label or aria-labelledby for radio buttons
without descriptive text content. For dynamic labels and descriptions, MatRadioButton
provides input properties for binding aria-label, aria-labelledby, and aria-describedby.
This means that you should not use the attr. prefix when binding these properties, as
demonstrated below.

<mat-radio-button [aria-label]="getMultipleChoiceAnswer()">

</mat-radio-button>

Prefer placing all radio buttons inside of a <mat-radio-group> rather than creating
standalone radio buttons because groups are easier to use exclusively with a keyboard.

You should provide an accessible label for all <mat-radio-group> elements via aria-label

4.13 Patch Forms Values,

2. patchValue() function

patchValue() function is used to set the value of reactive form controls.

example code,

patchValueExample() {

this.myForm.patchValue({

firstName: 'UpdatedFirstName',

lastName: 'UpdatedLastName',

});

use case scenario,

We use the patchValue() function when we do not want to update all the controls of the
reactive form, we can fill partial controls of the form.

For example, let’s say there is one optional input of the form and user did not fill that
input, and we store that value as a null or empty string in the database. So when filling
the form controls, we might not want to update or fill this input control. This is when we
can use patch value as it allows us to fill partial form controls.

4.14 Resetting Templates form Forms,


esetting a template-driven form in Angular involves clearing the form fields and resetting
their state to their initial values or empty values. You can achieve this by accessing the
form instance in your component class and calling the reset() method provided by
Angular's NgForm directive.

Here's how you can reset a template-driven form in Angular:

Accessing the Form Reference: First, you need to create a reference to the form in your
template using the ngForm directive.

<form #myForm="ngForm">

<!-- Form controls -->

</form>

Resetting the Form: In your component class, you can access the form reference using
the ViewChild decorator and call the reset() method on the form instance.

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

import { NgForm } from '@angular/forms';

@Component({

selector: 'app-my-component',

templateUrl: './my-component.component.html',

styleUrls: ['./my-component.component.css']

})

export class MyComponent {

@ViewChild('myForm') myForm: NgForm;

resetForm() {

this.myForm.resetForm();

}
Calling the Reset Method: You can then call the resetForm() method in your component
to reset the form.

<button type="button" (click)="resetForm()">Reset Form</button>

By calling the resetForm() method, Angular will reset the form to its initial state, clearing
all form fields and resetting their values and validation states. Additionally, it will mark
the form as pristine (not dirty) and untouched. This ensures that the form is in a clean
state, ready for new user input.

4.15 Reactive Forms,

Reactive forms in Angular provide a powerful and flexible way to manage form data in
your application. Unlike template-driven forms, where the form structure and behavior
are defined primarily in the HTML template, reactive forms are built programmatically in
the component class.

Here's how you can work with reactive forms in Angular:

1. Import ReactiveFormsModule: Make sure you have the ReactiveFormsModule


imported in your Angular module file (usually app.module.ts).

import { ReactiveFormsModule } from '@angular/forms';

Add ReactiveFormsModule to the imports array within the @NgModule decorator.

2. Create Form Controls: Define form controls using the FormControl class provided
by Angular's forms module.

import { FormGroup, FormControl } from '@angular/forms';

export class MyComponent {

myForm: FormGroup;

constructor() {

this.myForm = new FormGroup({

name: new FormControl(''),

email: new FormControl('')

});
}

3. Bind Form Controls in HTML Template: Bind the form controls defined in the
component class to form elements in the HTML template using the
formControlName directive.

<form [formGroup]="myForm">

<input type="text" formControlName="name">

<input type="email" formControlName="email">

</form>

4. Handling Form Submission: Handle form submission by subscribing to the


(ngSubmit) event on the <form> element and implementing a method in the
component class.

<form [formGroup]="myForm" (ngSubmit)="onSubmit()">

<!-- Form controls -->

<button type="submit">Submit</button>

</form>

typescript

Copy code

onSubmit() {

if (this.myForm.valid) {

console.log(this.myForm.value); // Access form data

// Perform other actions like sending data to server

5. Adding Validation: Add validation rules to form controls by passing validators as


the second argument to the FormControl constructor.
import { Validators } from '@angular/forms';

this.myForm = new FormGroup({

name: new FormControl('', Validators.required),

email: new FormControl('', [Validators.required, Validators.email])

});

Reactive forms offer more control and flexibility compared to template-driven forms,
making them suitable for complex forms and dynamic form structures. They also
provide better testability and maintainability since the form logic is defined in the
component class

4.16 What is Reactive Forms,

Reactive forms in Angular are a technique for creating and managing forms
programmatically within the component class. Unlike template-driven forms, where the
form structure and logic are primarily defined in the HTML template, reactive forms are
built using the FormBuilder service and FormControl, FormGroup, and FormArray
classes provided by Angular's ReactiveFormsModule module.

Here's a breakdown of the key concepts and benefits of reactive forms:

1. FormControl: Represents an individual form control such as an input field or


select box. FormControl instances are created for each form field and used to
track the value and validation state of the corresponding input element.
2. FormGroup: Groups multiple form controls together into a single form group.
FormGroup instances are used to manage the state of a group of form controls
and apply validation rules across the group.
3. FormArray: Manages an array of form controls. FormArray instances are used to
handle dynamic forms with a variable number of input fields, such as lists or
arrays of data.
4. FormBuilder: A service provided by Angular for creating instances of FormGroup,
FormControl, and FormArray more easily and concisely. It offers methods for
defining form controls and their initial values and validators in a fluent and
declarative way.

Reactive forms offer several advantages over template-driven forms:

● Greater Control: Since the form logic is defined in the component class,
developers have more control over form behavior and can implement complex
validation rules and dynamic form structures more easily.
● Better Testability: Reactive forms make it easier to write unit tests for form-related
logic since the form controls and their behavior are managed programmatically
within the component class.
● Improved Performance: Reactive forms can offer better performance for large
forms or forms with dynamic elements, as they avoid the overhead of two-way
data binding and change detection associated with template-driven forms.
● Reusability: Reactive forms can be more easily reused across different
components or even shared as custom form controls, making them a more
scalable solution for building forms in large applications.

4.16 Create Reactive form through code.

let's create a simple reactive form in Angular using code. We'll use the FormBuilder
service to create the form controls and group them into a FormGroup. In this example,
we'll create a form with two fields: name and email.

1. Import Required Modules: Ensure you have the ReactiveFormsModule imported


in your Angular module file (usually app.module.ts).

import { ReactiveFormsModule } from '@angular/forms';

Add ReactiveFormsModule to the imports array within the @NgModule decorator.

2. Create Reactive Form in Component Class: In your component class, import


FormBuilder and use it to create a FormGroup with form controls.

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

import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({

selector: 'app-my-component',

templateUrl: './my-component.component.html',

styleUrls: ['./my-component.component.css']

})

export class MyComponent implements OnInit {

myForm: FormGroup;
constructor(private formBuilder: FormBuilder) { }

ngOnInit() {

this.myForm = this.formBuilder.group({

name: ['', Validators.required],

email: ['', [Validators.required, Validators.email]]

});

onSubmit() {

if (this.myForm.valid) {

console.log(this.myForm.value); // Access form data

// Perform other actions like sending data to server

3. Bind Form Controls in HTML Template: In the HTML template, bind the form
controls defined in the component class to form elements using the
formControlName directive.

<form [formGroup]="myForm" (ngSubmit)="onSubmit()">

<div>

<label for="name">Name:</label>

<input type="text" id="name" formControlName="name">


<div *ngIf="myForm.controls['name'].invalid && (myForm.controls['name'].dirty ||
myForm.controls['name'].touched)">

<div *ngIf="myForm.controls['name'].errors.required">Name is required</div>

</div>

</div>

<div>

<label for="email">Email:</label>

<input type="email" id="email" formControlName="email">

<div *ngIf="myForm.controls['email'].invalid && (myForm.controls['email'].dirty ||


myForm.controls['email'].touched)">

<div *ngIf="myForm.controls['email'].errors.required">Email is required</div>

<div *ngIf="myForm.controls['email'].errors.email">Invalid email format</div>

</div>

</div>

<button type="submit" [disabled]="myForm.invalid">Submit</button>

</form>

In this example, we used FormBuilder to create a FormGroup with two form controls:
name and email. We added validation rules for the email field using Validators.required
and Validators.email. The form is bound to the myForm property in the component
class, and the onSubmit() method is called when the form is submitted. The form
submission is disabled if the form is invalid.

***************************************************************************************************

You might also like