Angular MScIT Sem2
Angular MScIT Sem2
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.
● 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:
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.
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.
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
<!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:
<script
src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
...
</div>
● Step 4: Bind the value of above model defined using ng-bind directive
<p>Hello <span ng-bind = "name"></span>!</p>
testAngularJS.htm
Live Demo
<html>
<head>
</head>
<body>
<h1>Sample Application</h1>
</div>
</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
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.
myApp.component('helloWorld', {
controller: function() {
this.name = 'World';
});
<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.
<!DOCTYPE html>
<meta charset="UTF-8">
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script
>
</head>
<body>
<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).
Components are the most basic UI building block of an Angular app. An Angular app
contains a tree of Angular components.
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.
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
@Component({
selector: 'app-hello',
templateUrl: './hello.component.html',
styleUrls: ['./hello.component.css']
})
export class HelloComponent {
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
@Component({
selector: 'app-hello',
templateUrl: './hello.component.html',
styleUrls: ['./hello.component.css']
})
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.
@Component({
selector: 'app-hello',
templateUrl: './hello.component.html',
styleUrls: ['./hello.component.css']
})
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.
<div>
</div>
/* 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
@NgModule({
declarations: [
HelloComponent
],
imports: [
BrowserModule
],
bootstrap: [HelloComponent]
})
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-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.
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:
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.
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.
Angular:
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.
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>
`,
})
export class HeroAppComponent {
/* . . . */
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.
Approach:
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">
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
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:
<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:
●
● 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.
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.
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:
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.
username = 'JohnDoe';
});
In the template, you can bind the FormControl's value to the corresponding input
field using property binding:=
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
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'})
src/app/hero-list.component.ts (constructor)
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
@Injectable({providedIn: 'root'})
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.
@Component({
standalone: true,
selector: 'app-hero-list',
templateUrl: './hero-list.component.html',
providers: [ HeroService ]
})
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
});
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.
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.
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
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:
This command will create a new service file named data.service.ts and a corresponding
unit test file.
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:
@Injectable({
providedIn: 'root'
})
constructor() { }
// Method to get all items
getItems(): string[] {
return this.items;
this.items.push(item);
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.
You can now inject the DataService into any Angular component where you want to use
it. For example, in a component's constructor:
@Component({
selector: 'app-example',
template: `
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>
})
items: string[];
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.
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.
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 {
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!
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.
@Injectable({
providedIn: 'root'
})
constructor() { }
@Injectable({
providedIn: 'root'
})
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.
@Injectable({
providedIn: 'root'
})
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.
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:
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.
@Injectable({
providedIn: 'root'
})
sharedData: string;
constructor() { }
this.sharedData = data;
}
getData(): string {
return this.sharedData;
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.
@Component({
selector: 'app-component-a',
template: `
<h1>Component A</h1>
})
setData(): void {
@Component({
selector: 'app-component-b',
template: `
<h1>Component B</h1>
})
getData(): string {
return this.dataService.getData();
Once the service is injected into the components, you can access its methods and
properties within the component's methods or templates.
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.
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:
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:
3.Router Navigation:
4.Route Parameters:
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:
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:
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:
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:
<span>
<ul>
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>
.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>
[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:
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.
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:
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');
ngOnInit(): void {
this.route.params.subscribe(params => {
const id = params['id'];
});
****************************************************************************************************
UNIT-IV: Forms in Angular JS
<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.
myForm: FormGroup;
this.myForm = this.fb.group({
});
onSubmit() {
if (this.myForm.valid) {
console.log(this.myForm.value);
<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.
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:
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.
<label for="name">Name:</label>
<label for="email">Email:</label>
<button type="submit">Submit</button>
</form>
onSubmit() {
if (myForm.form.valid) {
console.log(this.user);
// Perform other actions like sending data to server
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
constructor(
){ }
2. The form layout and details are defined in the HeroFormComponent class.
src/app/hero-form/hero-form.component.ts (v1)
@Component({
selector: 'app-hero-form',
templateUrl: './hero-form.component.html',
styleUrls: ['./hero-form.component.css']
})
submitted = false;
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.
'Leslie Rollover');
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
@NgModule({
imports: [
BrowserModule,
CommonModule,
FormsModule
],
declarations: [
AppComponent,
HeroFormComponent
],
providers: [],
bootstrap: [ AppComponent ]
})
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/[email protected]/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">
</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.
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.
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.
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.
</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".
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
<h1>{{firstname}}</h1>
</div>
<script>
app.controller('myCtrl', function($scope) {
$scope.firstname = "John";
$scope.lastname = "Doe";
});
</script>
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
Individual radio-buttons inside of a radio-group will inherit the name of the group.
The default color for radio buttons can be configured globally using the
MAT_RADIO_DEFAULT_OPTIONS provider
providers: [{
provide: MAT_RADIO_DEFAULT_OPTIONS,
}]
Accessibility
<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
2. patchValue() function
example code,
patchValueExample() {
this.myForm.patchValue({
firstName: 'UpdatedFirstName',
lastName: 'UpdatedLastName',
});
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.
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>
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.
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
resetForm() {
this.myForm.resetForm();
}
Calling the Reset Method: You can then call the resetForm() method in your component
to reset the form.
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.
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.
2. Create Form Controls: Define form controls using the FormControl class provided
by Angular's forms module.
myForm: FormGroup;
constructor() {
});
}
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">
</form>
<button type="submit">Submit</button>
</form>
typescript
Copy code
onSubmit() {
if (this.myForm.valid) {
});
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
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.
● 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.
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.
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
myForm: FormGroup;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.myForm = this.formBuilder.group({
});
onSubmit() {
if (this.myForm.valid) {
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.
<div>
<label for="name">Name:</label>
</div>
</div>
<div>
<label for="email">Email:</label>
</div>
</div>
</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.
***************************************************************************************************