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(); }

Thursday, March 25, 2021

What is the startup class in ASP.NET core?

 Startup class is the entry point of the ASP.NET Core application. Every .NET Core application must have this class. This class contains the application configuration rated items. It is not necessary that class name must "Startup", it can be anything, we can configure startup class in Program class.

public class Program

 {

 public static void Main(string[] args)

 {

 CreateWebHostBuilder(args).Build().Run();

 }

 

 public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>

 WebHost.CreateDefaultBuilder(args)

 .UseStartup<TestClass>();

 }

StringBuilder in C#

StringBuilder is a mutable string class in C# that provides better performance than the standard string class when you need to perform multiple string manipulations.

Key features of StringBuilder:

  1. It's located in the System.Text namespace
  2. It's mutable (unlike string, which is immutable)
  3. More efficient for multiple string operations
  4. Particularly useful when concatenating many strings

Basic usage:


using System;
using System.Text;

class Program
{
    static void Main()
    {
        // Create a new StringBuilder
        StringBuilder sb = new StringBuilder();
        
        // Append text
        sb.Append("Hello");
        sb.Append(" ");
        sb.Append("World!");
        
        // Convert to string when done
        string result = sb.ToString();
        
        Console.WriteLine(result); // Outputs: Hello World!
    }
}

Common methods:

  • Append() - Adds text to the end
  • AppendLine() - Adds text with a line break
  • Insert() - Inserts text at a specified position
  • Remove() - Removes characters
  • Replace() - Replaces specified characters
  • Clear() - Removes all characters
  • ToString() - Converts to a string

StringBuilder is particularly valuable in loops or when you're building strings iteratively, as it avoids creating multiple string objects in memory.

Would you like me to explain any specific aspect of StringBuilder in more detail?

Tuesday, March 23, 2021

we will understand how to set up middleware. Middleware in ASP.NET Core controls how our application responds to HTTP requests. It can also control how our application looks when there is an error, and it is a key piece in how we authenticate and authorize a user to perform specific actions.

 

  • Middleware are software components that are assembled into an application pipeline to handle requests and responses.

  • Each component chooses whether to pass the request on to the next component in the pipeline, and can perform certain actions before and after the next component is invoked in the pipeline.

  • Request delegates are used to build the request pipeline. The request delegates handle each HTTP request.

  • Each piece of middleware in ASP.NET Core is an object, and each piece has a very specific, focused, and limited role.

  • Ultimately, we need many pieces of middleware for an application to behave appropriately.

  • Let us now assume that we want to log information about every request into our application.

  • In that case, the first piece of middleware that we might install into the application is a logging component.

  • This logger can see everything about the incoming request, but chances are a logger is simply going to record some information and then pass along this request to the next piece of middleware.

  • Middleware is a series of components present in this processing pipeline.

  • The next piece of middleware that we've installed into the application is an authorizer.

  • An authorizer might be looking for specific cookie or access tokens in the HTTP headers.

  • If the authorizer finds a token, it allows the request to proceed. If not, perhaps the authorizer itself will respond to the request with an HTTP error code or redirect code to send the user to a login page.

  • But, otherwise, the authorizer will pass the request to the next piece of middleware which is a router.

  • A router looks at the URL and determines your next step of action.

  • The router looks over the application for something to respond to and if the router doesn't find anything to respond to, the router itself might return a 404 Not Found error.


Monday, March 22, 2021

Dependency Injection

 Dependency Injection (DI) is a design pattern used to implement IoC. It allows the creation of dependent objects outside of a class and provides those objects to a class through different ways. Using DI, we move the creation and binding of the dependent objects outside of the class that depends on them.

The Dependency Injection pattern involves 3 types of classes.

  1. Client Class: The client class (dependent class) is a class which depends on the service class
  2. Service Class: The service class (dependency) is a class that provides service to the client class.
  3. Injector Class: The injector class injects the service class object into the client class.