Showing posts with label angular caching. Show all posts
Showing posts with label angular caching. Show all posts

Saturday, November 8, 2025

🧩 Best Practices for Angular 16+ with .NET Core

 

🔹 1. Code Reusability in Angular

Reusable code saves time, reduces duplication, and improves maintainability.

✅ Best Practices:

a. Use Shared Modules

Create a dedicated SharedModule for commonly used components, directives, and pipes.

// shared/shared.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { HighlightDirective } from './highlight.directive'; import { DateFormatPipe } from './date-format.pipe'; @NgModule({ declarations: [HighlightDirective, DateFormatPipe], imports: [CommonModule, FormsModule], exports: [CommonModule, FormsModule, HighlightDirective, DateFormatPipe] }) export class SharedModule {}

Then import it in feature modules:

@NgModule({ imports: [SharedModule], }) export class EmployeeModule {}

b. Reusable Components

Create generic UI components like modals, dropdowns, and tables.

// shared/components/confirm-dialog/confirm-dialog.component.ts @Component({ selector: 'app-confirm-dialog', template: ` <h3>{{title}}</h3> <p>{{message}}</p> <button (click)="onConfirm()">OK</button> <button (click)="onCancel()">Cancel</button> ` }) export class ConfirmDialogComponent { @Input() title = ''; @Input() message = ''; @Output() confirm = new EventEmitter<boolean>(); onConfirm() { this.confirm.emit(true); } onCancel() { this.confirm.emit(false); } }

🔹 2. Caching for Performance

Caching reduces API calls and improves responsiveness.

✅ Best Practices:

a. Use Angular HTTP Interceptors for Caching

// core/interceptors/cache.interceptor.ts @Injectable() export class CacheInterceptor implements HttpInterceptor { private cache = new Map<string, any>(); intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { if (req.method !== 'GET') return next.handle(req); const cachedResponse = this.cache.get(req.url); if (cachedResponse) return of(cachedResponse); return next.handle(req).pipe( tap(event => { if (event instanceof HttpResponse) this.cache.set(req.url, event); }) ); } }

Add it in providers:

providers: [ { provide: HTTP_INTERCEPTORS, useClass: CacheInterceptor, multi: true } ]

b. Leverage Browser Storage

Use localStorage or IndexedDB to persist data.

localStorage.setItem('user', JSON.stringify(user)); const user = JSON.parse(localStorage.getItem('user')!);

🔹 3. Performance Improvements

✅ Best Practices:

a. Use OnPush Change Detection

For performance-sensitive components:

@Component({ selector: 'app-user-card', templateUrl: './user-card.component.html', changeDetection: ChangeDetectionStrategy.OnPush }) export class UserCardComponent { @Input() user!: User; }

b. Lazy Loading Modules

Split large apps into lazy-loaded modules.

// app-routing.module.ts const routes: Routes = [ { path: 'employee', loadChildren: () => import('./employee/employee.module').then(m => m.EmployeeModule) } ];

c. Use trackBy in ngFor

Reduces DOM re-rendering:

<tr *ngFor="let emp of employees; trackBy: trackById"> <td>{{emp.name}}</td> </tr>
trackById(index: number, item: any) { return item.id; }

d. Minimize API Calls

Use RxJS shareReplay() for shared observables:

employees$ = this.http.get<Employee[]>('/api/employees').pipe(shareReplay(1));

e. Server-Side Pagination & Filtering

Instead of loading all data:

// .NET Core API [HttpGet] public async Task<IActionResult> GetEmployees(int page = 1, int size = 10) { var data = await _context.Employees.Skip((page-1)*size).Take(size).ToListAsync(); return Ok(data); }

🔹 4. Security Best Practices

✅ a. JWT Authentication

Use short-lived JWT tokens for secure API calls.

.NET Core (Backend)

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidIssuer = Configuration["Jwt:Issuer"], ValidAudience = Configuration["Jwt:Audience"], ValidateLifetime = true, IssuerSigningKey = new SymmetricSecurityKey( Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]) ) }; });

Angular (Frontend)

// core/interceptors/auth.interceptor.ts @Injectable() export class AuthInterceptor implements HttpInterceptor { intercept(req: HttpRequest<any>, next: HttpHandler) { const token = localStorage.getItem('token'); const cloned = req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }); return next.handle(cloned); } }

✅ b. Sanitize User Input

Use Angular’s built-in sanitization:

this.safeHtml = this.sanitizer.bypassSecurityTrustHtml(userInput);

✅ c. Avoid Sensitive Data in Client Storage

Never store passwords or API keys in localStorage.

✅ d. Enable HTTPS and CORS Properly

app.UseHttpsRedirection(); app.UseCors(builder => builder.WithOrigins("https://your-angular-app.com") .AllowAnyHeader() .AllowAnyMethod());

🔹 5. Architecture Best Practices

✅ a. Organize Project Structure

/src /app /core /services /interceptors /shared /components /pipes /features /employee /products

✅ b. Use Interfaces and Models

export interface Employee { id: number; name: string; email: string; }

✅ c. Follow SOLID Principles

Keep components small and service-driven.


🔹 6. Example: Angular + .NET Core Integration

Angular Service

@Injectable({ providedIn: 'root' }) export class EmployeeService { private apiUrl = environment.apiBaseUrl + '/employees'; constructor(private http: HttpClient) {} getEmployees(page = 1, size = 10): Observable<Employee[]> { return this.http.get<Employee[]>(`${this.apiUrl}?page=${page}&size=${size}`); } }

.NET Core Controller

[ApiController] [Route("api/[controller]")] public class EmployeesController : ControllerBase { private readonly AppDbContext _context; public EmployeesController(AppDbContext context) => _context = context; [HttpGet] public async Task<IEnumerable<Employee>> GetEmployees(int page = 1, int size = 10) => await _context.Employees.Skip((page - 1) * size).Take(size).ToListAsync(); }

🔹 7. Tools and Optimization Tips

  • Angular CLI commands for performance:

    ng build --configuration production
  • Enable Ahead-of-Time (AOT) compilation

  • Use ngx-translate for i18n

  • Use Service Workers for offline caching (PWA)


✨ Conclusion

Building enterprise-grade apps using Angular 16+ and .NET Core requires balancing performance, maintainability, and security.
By following the above best practices — shared modules, lazy loading, caching, and JWT security — you can achieve high scalability and efficient app delivery.

Thursday, September 4, 2025

Angular Interview Preparation Guide for Experienced Developers

Angular has evolved into one of the most powerful front-end frameworks for building modern, scalable, and enterprise-level applications. For developers of experienced, interviews not only test your **theoretical knowledge** but also your **hands-on expertise** in building, deploying, and maintaining real-world Angular applications.


In this article, we’ll walk through the **key areas in Angular** you should master — starting from fundamentals to advanced production-ready concepts.


## 1. Angular Lifecycle Hooks


Lifecycle hooks are crucial for managing component creation, rendering, and destruction. Be prepared to explain **when and why** to use them.


* **ngOnInit**: Initialize component data.

* **ngOnChanges**: Detect changes in input-bound properties.

* **ngDoCheck**: Custom change detection.

* **ngAfterViewInit & ngAfterContentInit**: DOM and content initialization.

* **ngOnDestroy**: Cleanup, unsubscribe from Observables, release resources.


👉 **Interview Tip**: Be ready with real-time scenarios like unsubscribing in `ngOnDestroy` to prevent memory leaks.


## 2. Routing & Navigation


Routing is the backbone of any Angular application. Understand:


* **RouterModule** setup with `forRoot()` and `forChild()`.

* **Lazy Loading** modules for performance optimization.

* **Child Routes & Wildcards** (`**` for 404 pages).

* **Route Guards** (AuthGuard, CanActivate, CanDeactivate, Resolve).

* **Preloading strategies** for balancing lazy loading with speed.


👉 Example: Use `AuthGuard` with JWT tokens to restrict access to secure routes.


## 3. Forms in Angular


Forms are everywhere in enterprise apps. You must be comfortable with both approaches:


* **Template-driven forms** (simple, quick setup, two-way binding).

* **Reactive forms** (more control, validation, and scalability).


Key concepts:


* FormControl, FormGroup, FormBuilder.

* Built-in and custom validators.

* Async validators (e.g., checking if a username already exists).

* Dynamic form generation.


## 4. Angular Material & UI Components


Angular Material provides ready-to-use UI components. Focus on:


* Data tables with sorting, pagination, filtering.

* Dialogs, snackbars, and modals.

* Responsive layouts using Flex Layout/Grid.

* Theming and customization.


👉 **Interview Tip**: Be able to explain how Angular Material improves productivity and consistency.


## 5. Dependency Injection (DI)


Angular’s DI system is core to writing maintainable code. Know:


* Provider scopes: root, feature module, component.

* Hierarchical injectors.

* `@Injectable({ providedIn: 'root' })` usage.

* Tree-shakable providers.

* Use cases of `InjectionToken`.


## 6. HTTP Interceptors & API Handling


Interceptors allow you to **modify requests/responses globally**. Key scenarios:


* Attaching **JWT tokens** to headers.

* Global error handling (e.g., redirect to login on `401 Unauthorized`).

* Request/response logging.

* Caching responses for performance.

## 7. Authentication & Authorization (JWT Implementation)


Almost every production app requires authentication. Learn how to:


* Store and manage JWT tokens securely (localStorage vs cookies).

* Refresh tokens.

* Use interceptors to attach tokens.

* Protect routes with AuthGuards.

* Role-based access control.


👉 **Hands-on Task**: Implement login/logout with JWT, refresh tokens, and secure route navigation.


## 8. Caching & Performance Optimization


Production-grade apps demand speed. Interviewers expect knowledge of:


* Browser caching strategies (LocalStorage, IndexedDB).

* API response caching via interceptors.

* `OnPush` change detection strategy.

* Lazy loading and preloading strategies.

* TrackBy with `*ngFor` to prevent re-rendering.


## 9. Server-Side Rendering (SSR) with Angular Universal


For SEO and performance, Angular Universal is important. Be ready to answer:


* How SSR improves **SEO** for Angular apps.

* Setting up Angular Universal.

* Handling API calls on the server vs client.

* Differences between CSR (Client-Side Rendering) and SSR.


## 10. Error Handling & Logging


Enterprise apps need solid error handling. Know how to:


* Use **ErrorHandler** class for global error handling.

* Implement custom error services.

* Log errors to monitoring tools (e.g., Sentry, Azure App Insights).

* Show user-friendly error messages.


## 11. State Management (NgRx / Services)


Large apps often use state management. You should:


* Understand RxJS and Observables deeply.

* Be able to explain state management with Services and BehaviorSubject.

* Know NgRx basics: Actions, Reducers, Effects, Store.

* When to choose NgRx vs simple service-based state management.


## 12. Production-Level Deployment


Finally, demonstrate deployment expertise:


* `ng build --prod` optimizations (AOT compilation, minification, tree-shaking).

* Hosting on **Azure, AWS, Firebase, or Nginx**.

* Environment configuration (`environment.ts`).

* CI/CD pipeline setup for Angular apps.

* Handling SSL, security headers, and API proxy configuration.


## Conclusion


For a experienced Angular developer, interviews focus less on syntax and more on **architecture, scalability, performance, and deployment**.


If you cover these areas thoroughly — from lifecycle hooks, routing, forms, interceptors, JWT, Angular Universal, to production deployment — you’ll not only crack interviews but also be confident in building enterprise-grade Angular applications.


✅ **Pro Tip**: Build a small end-to-end Angular project that includes authentication, lazy loading, caching, Angular Material UI, and SSR. This will help you confidently explain your real-world experience.



Don't Copy

Protected by Copyscape Online Plagiarism Checker

Pages