Angular Unit 2 QB Sol
Angular Unit 2 QB Sol
Angular Unit 2 QB Sol
UNIT –2
If you haven't already set up an Angular application, you can create one
using the Angular CLI (Command Line Interface). Open your terminal or
command prompt and run the following command:
```
ng new my-app
```
cd my-app
```
Replace `my-module` with the name you want to give to your module.
```typescript
@NgModule({
declarations: [], // Components, directives, and pipes belong to this
module.
imports: [CommonModule], // Other modules that this module requires.
exports: [], // Components, directives, and pipes to be used outside this
module.
providers: [], // Services to be provided at this module level.
})
export class MyModule { }
```
- `exports`: This array contains the list of components, directives, and pipes
that can be used outside this module.
- `providers`: This array contains the list of services that are provided at this
module level. Any service listed here will be available across all components
in this module.
Once the module is configured, you can use it in your application. For
example, you can import the module into your `AppModule` (the root module
of your application) or any other feature module. Open the `app.module.ts`
file (located in the `src/app` directory) and import your module:
```typescript
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
MyModule // Include your module here
],
providers: [],
bootstrap: [AppComponent]
})
```html
<app-my-component></app-my-component>
```
1. **Core Module:**
The core module contains services, interceptors, and singleton objects that
are shared throughout the application. It ensures that core functionalities are
available globally and helps in organizing common features.
```typescript
@NgModule({
declarations: [],
imports: [
CommonModule,
HttpClientModule
],
providers: [
AuthService,
AuthInterceptor,
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
]
})
export class CoreModule { }
```
2. **Shared Module:**
The shared module contains components, directives, and pipes that are
commonly used across multiple feature modules. It helps in reducing code
duplication and ensures consistency across the application.
```typescript
@NgModule({
declarations: [
HeaderComponent,
FooterComponent,
SidebarComponent
],
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule
],
exports: [
HeaderComponent,
FooterComponent,
SidebarComponent,
FormsModule,
ReactiveFormsModule
]
})
3. **Authentication Module:**
The authentication module handles user authentication and authorization-
related features such as login, registration, and authentication guards.
```typescript
@NgModule({
declarations: [
LoginComponent,
RegistrationComponent
],
imports: [
CommonModule,
providers: [
AuthGuard
]
})
4. **Product Module:**
The product module manages product-related functionalities such as
product listing, details, search, and filtering.
```typescript
@NgModule({
declarations: [
ProductListComponent,
ProductDetailComponent
],
imports: [
CommonModule,
providers: [
ProductService
]
})
5. **Cart Module:**
The cart module manages shopping cart functionalities such as
adding/removing items, updating quantities, and checkout process.
```typescript
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { CartComponent } from './cart/cart.component';
@NgModule({
declarations: [
CartComponent,
CheckoutComponent
],
imports: [
CommonModule,
SharedModule // Reuse shared module components and directives
],
providers: [
CartService
]
})
export class CartModule { }
```
6. **Order Module:**
@NgModule({
declarations: [
OrderHistoryComponent,
OrderDetailComponent
],
imports: [
CommonModule,
SharedModule // Reuse shared module components and directives
],
providers: [
OrderService
]
})
export class OrderModule { }
```
**1. Modularity:**
Let's say you have an e-commerce application with separate modules for
product management, user authentication, and order processing:
```typescript
// Product Module
@NgModule({
declarations: [ProductListComponent, ProductDetailComponent],
@NgModule({
declarations: [LoginComponent, RegistrationComponent],
// Order Module
@NgModule({
declarations: [OrderHistoryComponent, OrderDetailComponent],
})
export class OrderModule {}
```
You can lazy load feature modules to improve initial load time and optimize
performance:
```typescript
const routes: Routes = [
{ path: 'products', loadChildren: () =>
import('./product/product.module').then(m => m.ProductModule) },
{ path: 'auth', loadChildren: () => import('./auth/auth.module').then(m =>
m.AuthModule) },
{ path: 'orders', loadChildren: () => import('./order/order.module').then(m
=> m.OrderModule) },
{ path: '', redirectTo: 'products', pathMatch: 'full' }
];
```
```typescript
// Product Service
@Injectable()
// Product Module
@NgModule({
providers: [ProductService]
})
export class ProductModule {}
```
3(ii). Explain the role of lazy loading in Angular modules and how it contributes
to application performance.
Lazy loading in Angular refers to the practice of loading modules only when
they are needed, rather than loading the entire application upfront. This
improves application performance by reducing the initial bundle size and load
time, especially for large-scale applications with multiple feature modules.
Here's how lazy loading works in Angular and how it contributes to application
performance:
3. **Faster Initial Load Time:** Since Angular loads only the essential
modules upfront and defers loading other modules until they are needed, the
initial load time of the application is greatly improved. Users can see and
interact with the core functionality of the application more quickly, enhancing
the overall user experience.
```typescript
// app-routing.module.ts
// Other routes...
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
1. **Define a Service:**
```typescript
// product.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root', // Register the service at the root level
})
export class ProductService {
getProducts() {
}
}
```
2. **Inject the Service into a Component:**
```typescript
// product-list.component.ts
@Component({
selector: 'app-product-list',
templateUrl: './product-list.component.html',
styleUrls: ['./product-list.component.css']
})
export class ProductListComponent implements OnInit {
products: string[];
ngOnInit(): void {
this.products = this.productService.getProducts();
}
}
```
3. **Use the Service in the Component Template:**
```html
<!-- product-list.component.html -->
<div>
<h2>Products</h2>
<ul>
</div>
```
In this example:
- The component template then iterates over the `products` array and
displays each product in a list.
This demonstrates how Dependency Injection allows you to inject services
into Angular components, making it easy to share functionality and data
across different parts of your application.