UNIT II Updated Notes
UNIT II Updated Notes
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
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.
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]
})
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
main.ts
First, make sure to import the HttpClientModule in your Angular module. You
typically do this in the app.module.ts file:
@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';
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);
});
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.
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:
@NgModule({
imports: [FormsModule],
// other module configurations
})
export class YourModule { }
<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>
@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:
@NgModule({
imports: [ReactiveFormsModule],
// other module configurations
})
export class YourModule { }
@Component({
selector: 'app-your-form',
templateUrl: './your-form.component.html',
})
export class YourFormComponent {
myForm: FormGroup;
onSubmit() {
// Handle form submission
console.log(this.myForm.value);
}
}
<label for="email">Email:</label>
<input type="email" id="email" formControlName="email">
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.
https://www.youtube.com/watch?v=0v1mQB4BCIo
1. Create a Service:
Use the Angular CLI to generate a service file:
2. Service Implementation:
Open the generated service file and implement your functionality. Here's a
simple example:
// your-service-name.service.ts
@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;
}
// your-component.component.ts
@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.
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:
@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:
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:
Example:
@Injectable({
providedIn: 'root',
})
export class MyService {
constructor(@Inject(MY_TOKEN) private myToken: string) {}
}
Besides classes, you can use value and factory providers to inject values or
create objects on the fly.
Example:
@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
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:
You can choose from prebuilt material design themes or set up an extensible
custom theme.
Let's display a slide toggle component in your app and verify that
everything works.
@NgModule ({
imports: [
MatSlideToggleModule,
]
})
class AppModule {}
<mat-slide-toggle>Toggle me!</mat-slide-toggle>
ng serve
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:
@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:
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:
This command generates a basic table component with Angular Material styles
and features.