0% found this document useful (0 votes)
20 views

UNIT II Updated Notes

Uploaded by

Dr. R. Gowri CIT
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

UNIT II Updated Notes

Uploaded by

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

UNIT II – ANGULAR MODULES AND MATERIAL

Angular Modules – HTTP client, Forms Module – Angular Service Files


– Dependency Injection – Angular Material – Connecting Angular with
Back End

Angular Modules
In Angular, a module is a mechanism to group components, directives,
pipes and services that are related, in such a way that can be combined with
other modules to create an application
Another analogy to understand Angular modules is classes. In a class, we
can define public or private methods. The public methods are the API that other
parts of our code can use to interact with it while the private methods are
implementation details that are hidden. In the same way, a module can export or
hide components, directives, pipes and services. The exported elements are
meant to be used by other modules, while the ones that are not exported
(hidden) are just used inside the module itself and cannot be directly accessed
by other modules of our application.

https://youtu.be/E-RXPC1OObs

A Basic Use of Modules

To be able to define modules we have to use the decorator NgModule.

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


@NgModule({
imports: [ ... ],
declarations: [ ... ],
bootstrap: [ ... ]
})
export class AppModule { }

In the example above, we have turned the class AppModule into an Angular
module just by using the NgModule decorator. The NgModule decorator
requires at least three properties: imports, declarations and bootstrap.

The property imports expects an array of modules. The property declarations


expects an array of components, directives and pipes that are part of the module.
The bootstrap property is where we define the root component of our module.
Even though this property is also an array, 99% of the time we are going to
define only one component.
There are very special circumstances where more than one component may be
required to bootstrap a module but we are not going to cover those edge cases
here.

Here's how a basic module made up of just one component would look like:

app/app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: '<h1>My Angular App</h1>'
})
export class AppComponent {}
app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule({
imports: [BrowserModule],
declarations: [AppComponent],
bootstrap: [AppComponent]
})

export class AppModule { }

The file app.component.ts is just a "hello world" component, nothing interesting


there. In the other hand, the file app.module.ts is following the structure that
we've seen before for defining a module but in this case, we are defining the
modules and components that we are going to be using.
The first thing that we notice is that our module is importing the
BrowserModule as an explicit dependency. The BrowserModule is a built-in
module that exports basic directives, pipes and services. Unlike previous
versions of Angular, we have to explicitly import those dependencies to be able
to use directives like *ngFor or *ngIf in our templates.
Given that the root (and only) component of our module is the AppComponent
we have to list it in the bootstrap array. Because in the declarations property we
are supposed to define all the components or pipes that make up our application,
we have to define the AppComponent again there too.

Before moving on, there's an important clarification to make. There are two
types of modules, root modules and feature modules.
In the same way that in a module we have one root component and many
possible secondary components, in an application we only have one root
module and zero or many feature modules. To be able to bootstrap our
application, Angular needs to know which one is the root module. An easy way
to identify a root module is by looking at the imports property of its NgModule
decorator. If the module is importing the BrowserModule then it's a root
module, if instead is importing the CommonModule then it is a feature module.
As developers, we need to take care of importing the BrowserModule in the root
module and instead, import the CommonModule in any other module we create
for the same application. Failing to do so might result in problems when
working with lazy loaded modules as we are going to see in following sections.
By convention, the root module should always be named AppModule.

Bootstrapping an Application

To bootstrap our module based application, we need to inform Angular which


one is our root module to perform the compilation in the browser. This
compilation in the browser is also known as "Just in Time" (JIT) compilation.
For the majority of our modules, we do not have to worry about this bootstrap
property, as the intended purpose is mostly to inform Angular of where the root
of our application tree begins.

main.ts

import { platformBrowserDynamic } from '@angular/platform-browser-


dynamic';
import { AppModule } from './app/app.module';
platformBrowserDynamic().bootstrapModule(AppModule);

It is also possible to perform the compilation as a build step of our workflow.


This method is called "Ahead of Time" (AOT) compilation and will require a
slightly different bootstrap process.

HTTP Client Module


https://www.youtube.com/watch?v=m3uG4oq5ei0

In Angular, the HttpClient module is part of the @angular/common/http


package and is used to make HTTP requests to a server. It provides a high-level
API for sending and receiving data over HTTP, making it easier to work with
web services and APIs.

Here's a basic overview of how to use the HttpClient module in Angular:


Import HttpClientModule:

First, make sure to import the HttpClientModule in your Angular module. You
typically do this in the app.module.ts file:

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

@NgModule({
imports: [HttpClientModule],
// other module configurations
})
export class AppModule { }

Inject HttpClient:

Next, inject the HttpClient service into your component or service where you
want to make HTTP requests. You can do this by adding it to the constructor:
import { HttpClient } from '@angular/common/http';

constructor(private http: HttpClient) { }

Making GET Requests:

You can use the get method to make a GET request. For example:

this.http.get('https://api.example.com/data').subscribe(data => {
// handle the response data
console.log(data);
});

Making POST Requests:

To make a POST request, you can use the post method:

const postData = { key: 'value' };

this.http.post('https://api.example.com/postData', postData).subscribe(response
=> {
// handle the response
console.log(response);
});

Handling Responses:

You handle the response using the subscribe method. This is where you can
process the data returned from the server.

this.http.get('https://api.example.com/data').subscribe(
data => {
// handle the successful response
console.log(data);
},
error => {
// handle errors
console.error('Error:', error);
}
);
Remember to handle errors appropriately by providing error handling functions
in the second parameter of the subscribe method.

This is a basic overview, and the HttpClient module provides many other
features and options for handling requests and responses.

HTTP client service features

 The ability to request typed response objects


 Streamlined error handling
 Testability features
 Request and response interception

Forms Module

https://youtu.be/-bGgjgx3fGs?si=mtwFMSDizYx_v0ir

In Angular, forms play a crucial role in handling user input and validation.
Angular provides two types of forms: template-driven forms and reactive forms.
The "forms" module in Angular refers to the features and functionality provided
by the @angular/forms module.

Template-Driven Forms:
Template-driven forms are created using directives in the template, such as
ngModel for two-way data binding. Here's a basic example:

1. Import the FormsModule:


In your module, import the FormsModule:
import { FormsModule } from '@angular/forms';

@NgModule({
imports: [FormsModule],
// other module configurations
})
export class YourModule { }

2. Use in the Template:


In your component's template, use the ngModel directive for two-way data
binding:

<form #myForm="ngForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name" [(ngModel)]="model.name"
required>

<label for="email">Email:</label>
<input type="email" id="email" name="email" [(ngModel)]="model.email"
required>

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


</form>

3. Access Form Values in the Component:


In your component, you can access the form values using the ngForm directive:

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

@Component({
selector: 'app-your-form',
templateUrl: './your-form.component.html',
})
export class YourFormComponent {
model: any = {}; // Model to store form data

onSubmit() {
// Handle form submission
console.log(this.model);
}
}

Reactive Forms:
Reactive forms are created programmatically using the FormBuilder service.
Here's a basic example:

1. Import the ReactiveFormsModule:


In your module, import the ReactiveFormsModule:

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

@NgModule({
imports: [ReactiveFormsModule],
// other module configurations
})
export class YourModule { }

2. Create the Form in the Component:

In your component, use the FormBuilder to create the form:

import { Component, FormBuilder, FormGroup, Validators } from


'@angular/core';

@Component({
selector: 'app-your-form',
templateUrl: './your-form.component.html',
})
export class YourFormComponent {
myForm: FormGroup;

constructor(private fb: FormBuilder) {


this.myForm = this.fb.group({
name: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],
});
}

onSubmit() {
// Handle form submission
console.log(this.myForm.value);
}
}

3. Use in the Template:


In your component's template, bind the form controls:

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


<label for="name">Name:</label>
<input type="text" id="name" formControlName="name">

<label for="email">Email:</label>
<input type="email" id="email" formControlName="email">

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


</form>

Both template-driven and reactive forms have their use cases, and the choice
between them depends on the specific requirements of your application.
Template-driven forms are more suitable for simple forms, while reactive forms
provide more flexibility and control for complex forms.

Angular Service Files


https://www.youtube.com/watch?v=B0FVAoG5srQ

https://www.youtube.com/watch?v=0v1mQB4BCIo

In Angular, service files are used to encapsulate and provide specific


functionality or data to different parts of an application. Services are a way to
organize and share code across components, directives, and other services. They
are typically responsible for handling data manipulation, making HTTP
requests, or performing other business logic.

Here's a basic guide on creating and using Angular service files:

1. Create a Service:
Use the Angular CLI to generate a service file:

ng generate service your-service-name


This command will create a service file (e.g., your-service-name.service.ts) and
an associated test file.

2. Service Implementation:
Open the generated service file and implement your functionality. Here's a
simple example:

// your-service-name.service.ts

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

@Injectable({
providedIn: 'root', // providedIn: 'root' makes the service a singleton and
automatically injects it where needed
})
export class YourServiceNameService {
private data: any[] = []; // Example data

getData(): any[] {
return this.data;
}

setData(newData: any[]): void {


this.data = newData;
}
}

3. Inject the Service:


Inject the service into the components or other services where you want to use
it. You can inject a service in the constructor of a component or another service:

// your-component.component.ts

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


import { YourServiceNameService } from './your-service-name.service';

@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
styleUrls: ['./your-component.component.css'],
})
export class YourComponent implements OnInit {
constructor(private yourService: YourServiceNameService) {}

ngOnInit(): void {
// Access the service methods here
const data = this.yourService.getData();
console.log(data);
}
}
4. Provider Registration:
Angular automatically provides services to components when they are
registered with the Angular dependency injection system. The providedIn: 'root'
in the @Injectable decorator is a shorthand for registering the service with the
root injector.

5. Dependency Injection:
Angular's dependency injection system takes care of creating and managing
instances of your service. When a component or another service requests the
service in its constructor, Angular injects the singleton instance.

6. Testing:
Angular CLI also generates a test file for your service. You can write unit tests
to ensure that your service functions as expected.

This basic guide should help you get started with creating and using Angular
service files. Remember that services are a powerful tool for organizing and
sharing code, promoting modularity, and improving the maintainability of your
Angular applications.

Dependency Injection
Dependency Injection (DI) is a design pattern and a fundamental concept in
software development, including Angular. It's a technique where one object or
service supplies the dependencies of another object. In the context of Angular,
DI is used to provide instances of services or other objects to components,
directives, or other services.

Here's how dependency injection works in Angular:

1. Service Registration:
Angular services need to be registered with the Angular dependency injection
system. This is typically done in the providers array of an Angular module or by
using the @Injectable decorator with the providedIn property.
// Service registration in a module
import { NgModule } from '@angular/core';
import { YourService } from './your-service';

@NgModule({
providers: [YourService],
// other module configurations
})
export class YourModule { }

2. Injecting Services:

You can inject services into components, directives, or other services by


including them in the constructor parameter:

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


import { YourService } from './your-service';

@Component({
selector: 'app-your-component',
templateUrl: './your-component.html',
})
export class YourComponent {
constructor(private yourService: YourService) {
// 'yourService' is now available for use within this component
}
}

3. Hierarchical Injector:

Angular has a hierarchical injector system. When a component requests a


service, Angular looks for the service in the following order:

 Component Injector: If the component itself has a provider for the


requested service, that instance is used.
 Ancestors: Angular looks up the injector hierarchy, checking parent
components and services.
 Module Injector: Finally, Angular checks the module injector. If the
service is not found, Angular throws an error.

4. Lazy Loading:
Angular supports lazy loading, where services are loaded only when they are
first requested. This helps improve application startup performance.

5. Injector Tokens:

Angular's DI system uses tokens to identify services or values. A token can be a


class or a string. When injecting a service, you use the token as the type of the
constructor parameter.

Example:

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

export const MY_TOKEN = new InjectionToken<string>('my-token');

@Injectable({
providedIn: 'root',
})
export class MyService {
constructor(@Inject(MY_TOKEN) private myToken: string) {}
}

6. Value and Factory Providers:

Besides classes, you can use value and factory providers to inject values or
create objects on the fly.

Example:

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

export const MY_VALUE = new InjectionToken<string>('my-value');


export const MY_FACTORY = new InjectionToken<string>('my-factory');

@NgModule({
providers: [
{ provide: MY_VALUE, useValue: 'Hello, World!' },
{ provide: MY_FACTORY, useFactory: () => 'Factory value' },
],
// other module configurations
})
export class YourModule { }
Angular's DI system provides a flexible and powerful way to manage
dependencies within an application, making code modular, maintainable, and
testable.

Angular Material
https://www.youtube.com/watch?v=AGjpMBcfwG4

Angular Material is a UI component library for Angular applications that


provides a set of high-quality and pre-built components following the Material
Design guidelines. It simplifies the process of building modern, responsive, and
visually appealing user interfaces in Angular applications.

Here are the key aspects of Angular Material:

1. Installation:
To use Angular Material in your Angular project, you need to install both
Angular Material and the Angular CDK (Component Dev Kit). You can do this
using the Angular CLI:

ng add @angular/material

The ng add command will install Angular Material, the Component Dev Kit
(CDK), Angular Animations and ask you the following questions to determine
which features to include:

Choose a prebuilt theme name, or "custom" for a custom theme:

You can choose from prebuilt material design themes or set up an extensible
custom theme.

Set up global Angular Material typography styles:

Whether to apply the global typography styles to your application.

Set up browser animations for Angular Material:

Importing the BrowserAnimationsModule into your application enables


Angular's animation system. Declining this will disable most of Angular
Material's animations.
The ng add command will additionally perform the following actions:

 Add project dependencies to package.json


 Add the Roboto font to your index.html
 Add the Material Design icon font to your index.html
 Add a few global CSS styles to:
 Remove margins from body
 Set height: 100% on html and body
 Set Roboto as the default application font
Angular Material is now configured to be used in your application.
Display a component

Let's display a slide toggle component in your app and verify that
everything works.

You need to import the MatSlideToggleModule that you want to display


by adding the following lines to your app.module.ts file.

import { MatSlideToggleModule } from '@angular/material/slide-


toggle';

@NgModule ({
imports: [
MatSlideToggleModule,
]
})
class AppModule {}

Add the <mat-slide-toggle> tag to the app.component.html like so:

<mat-slide-toggle>Toggle me!</mat-slide-toggle>

Run your local dev server:

ng serve

Then point your browser to http://localhost:4200

You should see the Material slide toggle component on the page.

2. Modules:

Angular Material is organized into several feature modules. You can import the
modules you need in your application module. Common modules include:

 MatButtonModule: Buttons
 MatInputModule: Input fields
 MatToolbarModule: Toolbars
 MatCardModule: Cards
 MatIconModule: Icons
 MatTableModule: Data tables
 MatDialogModule: Dialogs
 MatSnackBarModule: Snackbars/toasts

Example:

import { MatInputModule, MatButtonModule, MatToolbarModule } from


'@angular/material';

@NgModule({
imports: [MatInputModule, MatButtonModule, MatToolbarModule],
// other module configurations
})
export class YourMaterialModule { }

3. Component Usage:
Once you have imported the necessary modules, you can use Angular Material
components in your templates. For example:

<!-- Example using a Material button -->


<button mat-button>Click me</button>

<!-- Example using a Material input field -->


<mat-form-field>
<input matInput placeholder="Username">
</mat-form-field>

4. Theming:
Angular Material supports theming based on the Material Design color palette.
You can customize the theme by using the @angular/material/theming package
and importing pre-built themes or creating your own.

5. Customization:
While Angular Material provides a wide range of pre-built components, you can
also customize and extend them to suit the specific needs of your application.
6. Accessibility:
Angular Material components are designed with accessibility in mind, making it
easier to create applications that are usable by a wide range of users.

7. Documentation:
Refer to the official Angular Material documentation for detailed information,
including usage examples, API reference, and theming guidelines.

8. Schematics:
Angular Material includes schematics that can help you quickly generate
components, services, or modules related to Angular Material in your project.

For example:

ng generate @angular/material:table my-table

This command generates a basic table component with Angular Material styles
and features.

Using Angular Material can significantly speed up the development of your


Angular applications by providing a consistent and visually appealing set of UI
components that adhere to best practices.

You might also like