Saturday, April 19, 2025

What's New in Angular

 Angular has been evolving steadily with several significant updates in recent releases. Here are the key new features and improvements from the most recent versions:

Angular 17 (Late 2023)

  • Standalone APIs by default: New projects now use standalone components by default
  • Improved developer experience: New application starter with interactive CLI setup
  • Built-in control flow: New @if, @for, @switch syntax replacing *ngIf and *ngFor
  • Deferred loading: @defer block for lazy loading components
  • Server-side rendering improvements: Hydration is now on by default
  • Signals API improvements: More reactive programming capabilities
  • View transitions API: For smoother page transitions
  • New application builder: Based on Vite/esbuild instead of webpack

Angular 16 (May 2023)

  • Signals: Introduction of a new reactive primitive
  • Server-side rendering: Enhanced hydration support
  • Angular CLI: Further improvements with faster builds
  • Required inputs: Ability to mark @Input() fields as required
  • Self-closing tags: Support for components without content
  • Standalone components: Continued development of standalone API
  • Reactor: Early preview of new reactivity model

Angular 15 (November 2022)

  • Standalone components stable: No longer experimental
  • Directive composition API: Reuse directive behavior
  • Image directive: Automated image optimization
  • NgOptimizedImage: Performance improvements for images
  • esbuild support: Faster builds
  • Functional router guards: Simplified routing protection

Active Development Areas

Angular is currently focusing on several areas for future releases:

  1. Reactivity model enhancements: Expanding signals throughout the framework
  2. Performance improvements: Making Angular applications even faster
  3. Developer experience: Simplifying API usage and reducing boilerplate
  4. Build tooling: Moving away from webpack toward more modern build tools
  5. SSR and hydration: Enhanced server-side rendering capabilities

Looking ahead, Angular 18 is expected to bring further stabilization of signals and new features building on the reactive architecture introduced in recent versions.

Tuesday, April 15, 2025

Angular CLI Commands Cheat Sheet (2025 Edition)

 

⚡️ Angular CLI Commands Cheat Sheet

๐Ÿ“ฆ Project Setup

CommandDescription
ng new <project-name>Create a new Angular project
ng add <package>Add a package and run schematics (e.g., @angular/material)
ng configView or set config values in angular.json
ng analyticsEnable or disable analytics

๐Ÿš€ Serve & Build

CommandDescription
ng serveServe the app locally with hot reload
ng serve --port=4201Serve app on a custom port
ng buildBuild app for production
ng build --configuration=developmentBuild in dev mode
ng build --watchRebuild on file changes

๐Ÿ›  Generate Code (Schematics)

CommandDescription
ng generate component <name> or ng g c <name>Generate a component
ng g s <name>Generate a service
ng g m <name>Generate a module
ng g d <name>Generate a directive
ng g p <name>Generate a pipe
ng g i <name>Generate an interface
ng g guard <name>Generate a route guard
ng g class <name>Generate a TypeScript class

๐Ÿ“‚ Routing & Modules

CommandDescription
ng g module <name> --routingGenerate a module with routing
ng g component <name> --module=appRegister component in specific module
ng g module <name> --standaloneGenerate a standalone module/component (Angular 17+)

๐Ÿงช Testing

CommandDescription
ng testRun unit tests with Karma
ng test --watch=falseRun tests once and exit
ng e2eRun end-to-end tests (with Protractor or Cypress setup)

๐Ÿ“ˆ Linting, Format, & Analysis

CommandDescription
ng lintRun lint checks (ESLint if configured)
ng lint --fixAuto-fix lint errors
ng doc <keyword>Open Angular docs (e.g., ng doc directive)

๐Ÿ“ค Deployment & Misc

CommandDescription
ng deployDeploy via configured builder (e.g., Firebase, Netlify)
ng updateUpdate Angular CLI and core packages
ng versionShow Angular versions
ng helpList all CLI commands
ng cache cleanClear Angular build cache

๐Ÿ’ก Tips

  • Use --dry-run on any ng g command to preview changes.

  • Use --skip-tests if you don’t want spec files generated.

  • Combine flags like:
    ng g c user/profile --standalone --flat

How Generative AI is Transforming Angular Developers

 

๐Ÿง  1. Component Generation

  • Prompt to Code: With tools like GitHub Copilot, Codeium, or ChatGPT, Angular devs can write prompts like:

    "Create a responsive login form using Angular reactive forms with validation."

  • AI instantly scaffolds the component, HTML, styles, and even imports.

  • Saves time on boilerplate and encourages best practices.


๐Ÿ“ฆ 2. Service & HTTP Logic Automation

  • AI can auto-generate:

    • Angular services for REST APIs.

    • Proper use of HttpClient, RxJS, and error handling.

    • Token-based auth interceptors.

  • Result: Consistent, DRY, and secure data-fetching code.


๐Ÿ’… 3. Template & UI Design Help

  • Generate HTML/CSS for:

    • Material Design UI components.

    • Responsive layouts using Flexbox/Grid.

  • Prompt example:

    "Design a product card with Angular Material with an image, title, and 'Add to cart' button."

  • You can even use AI to:

    • Convert Figma designs into Angular components.

    • Suggest better UX/UI patterns.


๐Ÿ”„ 4. Two-Way Binding & State Management

  • AI can suggest optimal use of:

    • [(ngModel)] bindings.

    • @Input() / @Output() for parent-child communication.

    • State libraries like NgRx, Akita, or Signal-based state (Angular v17+).

  • Example: "Set up NgRx to manage user authentication state."


๐Ÿงช 5. Test Case Generation (Jasmine/Karma)

  • AI can:

    • Generate unit tests for components, pipes, and services.

    • Create mock data and testing modules.

  • Prompt:

    "Write Jasmine unit tests for an Angular login form component."

  • This massively reduces QA effort.


๐Ÿ“„ 6. Documentation & Code Comments

  • AI can:

    • Add inline comments to complex component logic.

    • Generate Markdown docs for services/components.

    • Help with documenting custom decorators, directives, and modules.


๐Ÿ› 7. Debugging & Refactoring Help

  • Explain error messages like:

    "NG0900: Error trying to diff '[object Object]'."

  • Suggests fixes or better patterns (e.g., using trackBy in *ngFor).

  • Can refactor legacy AngularJS or old Angular 2+ code into the latest best practices.


⚙️ 8. DevOps & Angular CLI

  • Generate or optimize:

    • angular.json, tsconfig.json, package.json.

    • Docker files for Angular apps.

    • Deployment configs (Firebase, Netlify, Vercel, AWS).


๐Ÿงฉ 9. Code Consistency & Style Enforcement

  • AI tools help enforce:

    • Linting rules (eslint, prettier).

    • Naming conventions.

    • Folder structures for scaling Angular apps.


๐Ÿ’ก 10. Learning & Upskilling

  • Junior Angular devs can learn in real-time by:

    • Asking AI to explain concepts like observables, ngZone, or ChangeDetectionStrategy.OnPush.

    • Getting feedback on architectural decisions.


๐ŸŒŸ Bonus: AI + Angular Tools You Can Try

  • GitHub Copilot – inline code gen and completions.

  • ChatGPT – natural language to Angular components/services.

  • Codeium / Cody / Tabnine – free code assistants.

  • Polarr AI for UI Generation – image/UI to code experiments.

Sunday, April 13, 2025

Build a Secure Login System with .NET Core + Angular

 Creating a secure login system with .NET Core (Backend) and Angular (Frontend) involves implementing industry best practices for authentication, such as JWT (JSON Web Tokens), password hashing, and role-based access control.

Here's a high-level breakdown of what to implement:

๐Ÿ” Backend (.NET Core) – Secure API with JWT

Tools/Packages:

  • .NET 7 or later

  • Microsoft.AspNetCore.Authentication.JwtBearer

  • EntityFrameworkCore

  • AutoMapper

  • FluentValidation (optional for DTO validation)

✅ Backend Features

  1. User Registration

    • Hash passwords using PasswordHasher<TUser>

    • Store user info in a SQL database (e.g., SQL Server)

  2. Login & JWT Generation

    • Authenticate credentials

    • Return JWT token on successful login

  3. Secure Endpoints

    • Use [Authorize] attribute

    • Role-based authorization via claims

  4. Token Validation

    • Middleware to validate JWT tokens in headers

  5. Refresh Token (Optional for extra security)


๐Ÿ”ง Sample .NET Code (Key Snippets)

Startup.cs / Program.cs (Service Config)

csharp

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

Generate JWT Token

csharp

public string GenerateToken(ApplicationUser user) { var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, user.UserName), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) }; var creds = new SigningCredentials( new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"])), SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: _config["Jwt:Issuer"], audience: _config["Jwt:Audience"], claims: claims, expires: DateTime.Now.AddMinutes(30), signingCredentials: creds); return new JwtSecurityTokenHandler().WriteToken(token); }

๐ŸŒ Frontend (Angular) – Login UI + Token Handling

✅ Angular Features

  1. Login Form with Angular Reactive Forms

  2. AuthService to manage token-based login

  3. Http Interceptor to append JWT token to HTTP requests

  4. Route Guards to restrict access to secure routes


๐Ÿ”ง Angular Key Snippets

AuthService.ts

ts

login(credentials: any): Observable<any> { return this.http.post('https://your-api-url/api/auth/login', credentials) .pipe(tap((res: any) => { localStorage.setItem('token', res.token); })); } isLoggedIn(): boolean { return !!localStorage.getItem('token'); }

Auth Interceptor

ts

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const token = localStorage.getItem('token'); if (token) { req = req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }); } return next.handle(req); }

Route Guard

ts

canActivate(): boolean { return this.authService.isLoggedIn(); }