Full Trust European Hosting

BLOG about Full Trust Hosting and Its Technology - Dedicated to European Windows Hosting Customer

AngularJS Hosting Europe - HostForLIFE :: Using Web Workers to Optimize Angular Performance for Complex Calculations

clock November 13, 2025 09:09 by author Peter

Performance and responsiveness are important aspects of the user experience in contemporary single-page applications (SPAs). Although Angular is a strong framework for creating dynamic apps, the user interface (UI) may become sluggish or unresponsive when your application must manage sophisticated mathematical operations, data processing, or significant computations. This occurs because Angular's programming language, JavaScript, operates in a single thread, which means that data processing, user interactions, and UI updates all vie for the same execution line.


 In order to address this issue, browsers offer a robust feature called Web Workers, which enables you to execute background operations concurrently without interfering with the main thread.

In this article, we’ll explore how to use Web Workers in Angular, understand when to use them, and walk through a step-by-step implementation for improving app performance with real-world examples.

What Are Web Workers?
Web Workers are background scripts that run independently from the main JavaScript thread.
They allow you to perform CPU-intensive tasks — like image processing, data encryption, or large JSON transformations — without freezing your UI.

Key characteristics

  • Run in a separate thread (parallel to the main UI).
  • Communicate via message passing (using postMessage() and onmessage).
  • Have no direct access to DOM or global variables.
  • Can perform complex logic or data manipulation safely.

Example scenario
Imagine processing a large dataset of 100,000 records in an Angular app. Doing this directly in a component method can cause UI lag.
With a Web Worker, the processing happens in the background, and once completed, the result is sent back — keeping your UI smooth and responsive.

When Should You Use Web Workers?
Use Web Workers when:
You’re performing CPU-heavy or long-running tasks:

  • Mathematical computations
  • Image or video encoding
  • Parsing large JSON or XML files
  • Cryptographic or hashing operations

Your Angular app experiences frame drops or freezing during data operations.
You want to keep animations and interactions smooth while processing data in the background.

Avoid Web Workers when:

  • The task is lightweight or runs instantly.
  • You need direct DOM access.
  • The overhead of message passing outweighs benefits.

Step-by-Step Implementation in Angular
Let’s implement a practical example to understand Web Workers in Angular.

We’ll create a Prime Number Calculator — a CPU-heavy task that can easily freeze the UI if executed in the main thread.

Step 1: Create a New Angular Project
If you don’t already have one:
ng new web-worker-demo
cd web-worker-demo


Step 2: Generate a Web Worker
Angular CLI provides built-in support for workers:
ng generate web-worker app

You’ll be asked:
? Would you like to add Angular CLI support for Web Workers? Yes

Once done, Angular automatically:
Updates tsconfig.json with "webWorker": true

Creates a new file: src/app/app.worker.ts

Step 3: Write Logic in the Worker File
Open src/app/app.worker.ts and add the heavy computation logic.
/// <reference lib="webworker" />

// Function to find prime numbers up to a given limitfunction generatePrimes(limit: number): number[] {
  const primes: number[] = [];
  for (let i = 2; i <= limit; i++) {
    let isPrime = true;
    for (let j = 2; j * j <= i; j++) {
      if (i % j === 0) {
        isPrime = false;
        break;
      }
    }
    if (isPrime) primes.push(i);
  }
  return primes;
}

// Listen for messages from main threadaddEventListener('message', ({ data }) => {
  const primes = generatePrimes(data);
  postMessage(primes);
});

This worker listens for a message containing a number limit, computes prime numbers up to that limit, and sends them back to the main Angular thread.

Step 4: Modify the Component

Open src/app/app.component.ts:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <div style="text-align:center; padding:20px;">
      <h2>Angular Web Worker Demo</h2>
      <input type="number" [(ngModel)]="limit" placeholder="Enter number" />
      <button (click)="calculate()">Generate Primes</button>
      <p *ngIf="loading">Calculating, please wait...</p>
      <div *ngIf="!loading && result.length">
        <h3>Prime Numbers:</h3>
        <p>{{ result.join(', ') }}</p>
      </div>
    </div>
  `,
})
export class AppComponent implements OnInit {
  limit = 100000;
  result: number[] = [];
  loading = false;
  worker!: Worker;

  ngOnInit(): void {
    if (typeof Worker !== 'undefined') {
      this.worker = new Worker(new URL('./app.worker', import.meta.url));
      this.worker.onmessage = ({ data }) => {
        this.result = data;
        this.loading = false;
      };
    } else {
      alert('Web Workers are not supported in this browser!');
    }
  }

  calculate() {
    this.loading = true;
    this.worker.postMessage(this.limit);
  }
}

Step 5: Enable FormsModule for ngModel
In app.module.ts, import the FormsModule:
import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, FormsModule],
  bootstrap: [AppComponent],
})
export class AppModule {}


Step 6: Run the Application
Run the Angular app:
ng serve

Open the browser at http://localhost:4200 and enter a large number like 100000.
Without Web Workers, the UI would freeze; now it remains smooth while computation happens in the background.

How It Works?

  • When the user clicks Generate Primes, the component sends a message to the Web Worker using postMessage().
  • The worker executes generatePrimes() in a separate thread.
  • Once computation finishes, the worker sends results back using postMessage().
  • The Angular component receives the result via onmessage and updates the UI.
Error Handling in Workers
You can also handle runtime errors gracefully.
this.worker.onerror = (error) => {
  console.error('Worker error:', error);
  this.loading = false;
};

Always include fallback logic if a browser doesn’t support Web Workers.

Terminating a Worker
If a user cancels an operation midway, terminate the worker:
if (this.worker) {
  this.worker.terminate();
}

This ensures memory is freed and no unnecessary computation continues in the background.

Advanced Example: JSON Data Processing
Suppose your Angular app downloads a 50MB JSON file and you want to filter and aggregate data efficiently.
Worker (data.worker.ts)

addEventListener('message', ({ data }) => {
  const result = data.filter((x: any) => x.isActive);
  postMessage(result.length);
});

Component
this.worker.postMessage(largeJsonArray);
this.worker.onmessage = ({ data }) => {
  console.log('Active records count:', data);
};

The computation runs in the worker thread, keeping your UI smooth.

Combining Web Workers with RxJS
You can wrap the Web Worker communication in an RxJS Observable for a cleaner and reactive design.
calculatePrimes(limit: number): Observable<number[]> {
  return new Observable((observer) => {
    const worker = new Worker(new URL('./app.worker', import.meta.url));
    worker.onmessage = ({ data }) => {
      observer.next(data);
      observer.complete();
      worker.terminate();
    };
    worker.onerror = (err) => observer.error(err);
    worker.postMessage(limit);
  });
}

This allows seamless integration with Angular’s reactive programming pattern.

Best Practices for Using Web Workers in Angular
Use Workers for CPU-Intensive Tasks Only
Avoid creating unnecessary workers for small operations.

Limit the Number of Workers
Each worker consumes memory; don’t overload the browser.

Terminate Workers When Not Needed
Prevent memory leaks by calling worker.terminate().

Serialize Data Efficiently
Minimize payload size when using postMessage().

Use SharedArrayBuffer (if needed)
For high-performance use cases, shared memory can reduce data transfer overhead.

Profile Performance
Use Chrome DevTools → Performance tab to measure improvement.

Integration with ASP.NET Core Backend
While Web Workers run in the browser, you can integrate them with your ASP.NET Core backend to optimize client-server performance.
For example:

The worker can pre-process data (filter, aggregate) before sending it to the API.

The API only receives minimal, structured data.

This combination reduces network payloads and API processing time — improving overall system efficiency.

Conclusion

Web Workers are one of the most underutilized features in frontend development. For Angular applications dealing with heavy computations or large data processing, using Web Workers can dramatically enhance performance and user experience. They ensure the main UI thread remains responsive, users experience smooth interactions, and complex tasks run efficiently in parallel.

By implementing Web Workers effectively — and combining them with Angular’s reactive ecosystem — developers can build high-performance, scalable web apps that deliver a desktop-like experience, even for complex workloads.


AngularJS Hosting Europe - HostForLIFE :: Using Angular 19 with ASP.NET Core 9 to Create a Scalable Web Application

clock November 12, 2025 07:12 by author Peter

The aim of every developer in contemporary web development is to create an application that is high-performing, scalable, and maintained.
A robust, modular, and cloud-ready full-stack solution may be achieved by combining Angular 19 for the frontend and ASP.NET Core 9 for the backend.

Developers looking for a realistic, hands-on approach covering everything from architecture setup to production deployment should read this article.

Why ASP.NET Core 9 + Angular 19?

FeatureAngular 19 (Frontend)ASP.NET Core 9 (Backend)
Language TypeScript C#
Rendering SSR + CSR + Hydration API-first
Build System Standalone components, Signals, ESBuild Minimal APIs, gRPC, Native AOT
Performance Improved reactivity model Optimized for microservices
Dev Tools Angular CLI 19, Vite .NET CLI, EF Core 9
Ideal Use SPAs, PWAs REST APIs, Web APIs, Services

Angular handles rich UI and real-time interaction, while ASP.NET Core delivers high-speed APIs and scalable backend logic.

Step 1: Architecture Design
A scalable architecture clearly delineates roles.

Step 2: Setting up the Backend (ASP.NET Core 9)
Create the API Project
dotnet new webapi -n ScalableApp.Api
cd ScalableApp.Api


Example: Model Class
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public decimal Price { get; set; }
}


Example: Repository Pattern
public interface IProductRepository
{
    Task<IEnumerable<Product>> GetAllAsync();
    Task<Product?> GetByIdAsync(int id);
    Task AddAsync(Product product);
}

public class ProductRepository : IProductRepository
{
    private readonly AppDbContext _context;
    public ProductRepository(AppDbContext context) => _context = context;

    public async Task<IEnumerable<Product>> GetAllAsync() => await _context.Products.ToListAsync();
    public async Task<Product?> GetByIdAsync(int id) => await _context.Products.FindAsync(id);
    public async Task AddAsync(Product product)
    {
        _context.Products.Add(product);
        await _context.SaveChangesAsync();
    }
}


Example: Controller
[ApiController]
[Route("api/[controller]")]
public class ProductController : ControllerBase
{
    private readonly IProductRepository _repository;
    public ProductController(IProductRepository repository) => _repository = repository;

    [HttpGet]
    public async Task<IActionResult> GetAll() => Ok(await _repository.GetAllAsync());
}


Step 3: Connect to SQL Server (EF Core 9)
Install EF Core
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools

Setup DbContext

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options) { }

    public DbSet<Product> Products => Set<Product>();
}

Register in Program.cs
builder.Services.AddDbContext<AppDbContext>(opt =>
    opt.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddScoped<IProductRepository, ProductRepository>();


Example appsettings.json
{"ConnectionStrings": {
    "DefaultConnection": "Server=localhost;Database=ScalableAppDB;Trusted_Connection=True;"}}


Step 4: Building the Frontend (Angular 19)
Create Angular App

ng new scalable-app --standalone
cd scalable-app
ng serve

Install Required Packages
npm install @angular/material @angular/forms @angular/common rxjs

Create a Product Service
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

export interface Product {
  id: number;
  name: string;
  price: number;
}

@Injectable({ providedIn: 'root' })
export class ProductService {
  private apiUrl = 'https://localhost:5001/api/product';

  constructor(private http: HttpClient) {}

  getAll(): Observable<Product[]> {
    return this.http.get<Product[]>(this.apiUrl);
  }
}


Display Products in Component
import { Component, OnInit, signal } from '@angular/core';
import { ProductService, Product } from '../services/product.service';

@Component({
  selector: 'app-product-list',
  standalone: true,
  template: `
    <h2>Product List</h2>
    <ul>
      <li *ngFor="let p of products()">
        {{ p.name }} - {{ p.price | currency }}
      </li>
    </ul>
  `
})
export class ProductListComponent implements OnInit {
  products = signal<Product[]>([]);

  constructor(private service: ProductService) {}

  ngOnInit() {
    this.service.getAll().subscribe(res => this.products.set(res));
  }
}


Step 5: Add Authentication (JWT + Angular Guard)
Backend (ASP.NET Core)

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = "https://yourapi.com",
            ValidAudience = "https://yourapp.com",
            IssuerSigningKey = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
        };
    });

Frontend (Angular 19 Guard)
import { CanActivateFn } from '@angular/router';
export const authGuard: CanActivateFn = () => {
  const token = localStorage.getItem('token');
  return !!token;
};

Step 6: Deployment Strategy
Angular Build for Production

ng build --configuration production

The build output will be in /dist/scalable-app.

ASP.NET Core Publish

dotnet publish -c Release -o ./publish

Host Both Together
Place Angular’s built files inside ASP.NET Core’s wwwroot folder.
Modify Program.cs:
app.UseDefaultFiles();
app.UseStaticFiles();
app.MapFallbackToFile("index.html");

Step 7: Best Practices for Scalability

AreaBest Practice
API Use async methods and pagination
Database Use stored procedures for heavy queries
Caching Add MemoryCache / Redis for repeated API calls
Logging Centralize logs with Serilog / Application Insights
Security Use HTTPS, JWT, and CORS configuration
Frontend Lazy load routes and use Angular Signals
DevOps Use CI/CD pipelines (GitHub Actions / Azure DevOps)

Step 8: CI/CD Integration
Example GitHub Actions pipeline for .NET + Angular:
name: Build and Deploy
on:push:
    branches: [ main ]

jobs:build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Setup .NET
        uses: actions/setup-dotnet@v4
        with:
          dotnet-version: '9.0.x'
      - name: Build .NET API
        run: dotnet publish ./ScalableApp.Api -c Release -o ./publish

      - name: Setup Node
        uses: actions/setup-node@v4
        with:
          node-version: '20'
      - name: Build Angular
        run: |
          cd scalable-app
          npm ci
          npm run build

Full-Stack Flow Diagram
[ Angular 19 UI ]
            |
(HTTP calls via HttpClient)
            ↓
   [ ASP.NET Core 9 API ]
            |
   [ Business Logic Layer ]
            |
   [ EF Core Repository ]
            |
   [ SQL Server Database ]


Conclusion
By combining Angular 19 and ASP.NET Core 9, you can build a robust, modular, and enterprise-grade web application that scales effortlessly.

Key takeaways:
Use layered architecture for clean separation of concerns.
Integrate EF Core 9 for fast database operations.
Apply JWT authentication for secure communication.
Deploy via CI/CD pipelines for efficiency and reliability.
With this setup, your web app is ready for both enterprise growth and modern cloud environments.



AngularJS Hosting Europe - HostForLIFE :: Using Angular Standalone Components and Signal APIs to Create High-Performance User Interfaces

clock November 4, 2025 06:45 by author Peter

Angular has made significant progress in recent years to improve runtime performance and simplify app structure. Developers can now create apps that load more quickly, operate more smoothly, and require less maintenance thanks to Angular Standalone Components and the new Signal API. This post will explain these capabilities, their significance, and how to combine them to create cutting-edge, lightning-fast Angular applications.

1. Standalone Components: What Are They?
In the past, each Angular component required to be a part of a NgModule.
However, you can create Standalone Components starting with Angular 14 and now fully stable with Angular 17+, so they don't need to be specified inside a module.

Example: Creating a Standalone Component
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-dashboard',
  standalone: true,
  imports: [CommonModule],
  template: `<h2>Welcome to Dashboard!</h2>`
})
export class DashboardComponent {}


No @NgModule needed!
You can directly use this component in routing or even bootstrap it in main.ts.

2. Bootstrapping with Standalone Components
With standalone components, even your AppModule becomes optional.
Example:
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';

bootstrapApplication(AppComponent)
  .catch(err => console.error(err));


That’s it no AppModule required!
This reduces overhead and speeds up the app’s initial load time.

3. Angular Signal API: The Game Changer

The Signal API, introduced in Angular 16+, is a powerful new way to manage reactive state without complex libraries like RxJS or NgRx.

Signals are reactive variables that automatically update the UI whenever their value changes.

Example: Simple Counter Using Signal
import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-counter',
  standalone: true,
  template: `
    <h2>Count: {{ count() }}</h2>
    <button (click)="increment()">Increment</button>
  `
})
export class CounterComponent {
  count = signal(0);

  increment() {
    this.count.update(c => c + 1);
  }
}


No BehaviorSubject, no subscriptions just simple, reactive code.

4. How Signals Improve Performance
With traditional change detection, Angular re-renders components unnecessarily.
Signals fix this by using fine-grained reactivity — only updating parts of the UI that actually change.

This means:

  • Less re-rendering
  • Better performance
  • Cleaner codebase

5. Combining Standalone Components and Signals
Together, Standalone Components and Signals make Angular apps simpler and more efficient.

Here’s an example of how both can be used in a real-world scenario like a Product Dashboard.
Example: Product Dashboard with Reactive State
import { Component, signal } from '@angular/core';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-product-dashboard',
  standalone: true,
  imports: [CommonModule],
  template: `
    <h1>Product Dashboard</h1>
    <input type="text" placeholder="Search product..." (input)="search($event)">
    <ul>
      <li *ngFor="let p of filteredProducts()">{{ p }}</li>
    </ul>
  `
})
export class ProductDashboardComponent {
  products = signal(['TV', 'Fridge', 'Laptop', 'Fan', 'Microwave']);
  filteredProducts = signal(this.products());

  search(event: any) {
    const keyword = event.target.value.toLowerCase();
    this.filteredProducts.set(
      this.products().filter(p => p.toLowerCase().includes(keyword))
    );
  }
}


Here:

  • Signals manage product lists.
  • Standalone Component keeps the code modular and fast.
  • The UI updates instantly without manual subscriptions.

6. Flowchart: How It Works
Below is a simple visual flow for your blog (you can design this using Canva or draw.io):

User Action (e.g., Click or Input)
          ↓
 Signal Updates (state change)
          ↓
 Angular detects signal change
          ↓
 Component Re-renders (only affected part)
          ↓
 UI Updates Instantly

This shows how Signals streamline UI updates with minimal re-rendering.

7. Responsive UI Example with PrimeNG

Now let’s combine Angular + PrimeNG to make a clean, responsive dashboard.
Example UI Structure

-------------------------------------
| Header: App Title + Menu Button   |
-------------------------------------
| Sidebar |     Main Dashboard      |
|         |  - Charts               |
|         |  - Stats Cards          |
|         |  - Product List         |
-------------------------------------

PrimeNG Components Used:
p-card for summary boxes
p-table for data grids
p-chart for performance visualization
p-sidebar for navigation

Example Snippet
<p-sidebar [(visible)]="menuVisible">
  <h3>Menu</h3>
  <p>Dashboard</p>
  <p>Reports</p>
</p-sidebar>

<p-card header="Total Sales">
  <h2>{{ totalSales() | currency }}</h2>
</p-card>

<p-chart type="bar" [data]="chartData()"></p-chart>

Your app becomes lighter, more modular, and boots up more quickly as a result. 
This gives a smooth, mobile-friendly dashboard that responds instantly due to Signals.

8. Performance Comparison

FeatureBefore (RxJS/Modules)Now (Signals/Standalone)

App Bootstrap

Slower

Faster

State Management

Complex

Simple

Change Detection

Broad

Fine-grained

Code Size

Larger

Smaller

Learning Curve

Steep

Easier

9. Real-World Benefits

  • Faster App Loading
  • Simplified Codebase
  • No Extra Libraries
  • Better Reusability
  • Improved UI Responsiveness

10. Conclusion
Angular is now quicker, lighter, and easier for developers to use thanks to Standalone Components and Signals. These capabilities allow you create contemporary, high-performance user interfaces with clear, reactive logic while streamlining structure and improving speed. Now is the ideal moment to update your Angular projects if you haven't already.



AngularJS Hosting Europe - HostForLIFE :: Database-Based Dynamic ActiveX Report in Angular

clock October 27, 2025 08:34 by author Peter

ActiveX reports are still used to generate and show comprehensive business reports (such as invoices, financial summaries, and logs) in a large number of enterprise-grade web applications, particularly those that are moving from legacy systems. Even though Internet Explorer has historically used ActiveX controls, you may still use other integration strategies to embed, create, and dynamically bind ActiveX reports from a database in contemporary Angular apps, like:

  • Using a COM-based backend API (C#/.NET) to render and serve reports
  • Embedding report viewers (like Crystal Reports, Stimulsoft, or ActiveReports) via iframe or custom web components
  • Fetching data dynamically via Angular services (HttpClient)

This article explains how to generate and display dynamic ActiveX-based reports from a SQL database in an Angular frontend.

Prerequisites
Before you start, ensure you have the following setup:

  • Angular 17+
  • .NET 6+ or .NET Framework 4.8 (for backend ActiveX/COM integration)
  • SQL Server Database
  • ActiveX or reporting tool (e.g., ActiveReports, Crystal Reports, or COM Report Engine)
  • Node.js and npm installed

Architecture Overview
The flow for generating the dynamic ActiveX report is as follows:
[Angular App] ---> [Web API / .NET Backend] ---> [Database (SQL Server)]
                                           ---> [ActiveX Report Engine]

  • Angular app sends a request (with parameters) to the backend.
  • Backend retrieves data from SQL Server.
  • Backend generates a report (ActiveX / COM report file).
  • Angular displays the generated report (via iframe or viewer component).

Step 1. Create a Backend API to Generate Reports
You can use a C# .NET Web API to handle the ActiveX or report engine integration.

Here’s a simple example of a backend controller (ReportController.cs):
[ApiController]
[Route("api/[controller]")]
public class ReportController : ControllerBase
{
    private readonly IConfiguration _config;

    public ReportController(IConfiguration config)
    {
        _config = config;
    }

    [HttpGet("GenerateReport")]
    public IActionResult GenerateReport(int reportId)
    {
        string connectionString = _config.GetConnectionString("DefaultConnection");

        // Fetch data from SQL Server
        var data = new DataTable();
        using (SqlConnection con = new SqlConnection(connectionString))
        {
            string query = "SELECT * FROM Sales WHERE ReportId = @ReportId";
            using (SqlCommand cmd = new SqlCommand(query, con))
            {
                cmd.Parameters.AddWithValue("@ReportId", reportId);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(data);
            }
        }

        // Use COM-based ActiveX Report Engine (e.g., ActiveReports)
        var report = new ActiveXReportLib.ReportClass();
        report.LoadTemplate("C:\\Reports\\SalesReport.rpt");
        report.SetDataSource(data);
        string pdfPath = $"C:\\Reports\\Output\\Report_{reportId}.pdf";
        report.ExportToPDF(pdfPath);

        return File(System.IO.File.ReadAllBytes(pdfPath), "application/pdf");
    }
}

This code:

  • Connects to SQL Server
  • Loads an ActiveX-based report template
  • Fills it with data
  • Exports it as PDF
  • Returns it to the frontend

Step 2. Create an Angular Service to Fetch the Report
In Angular, create a ReportService to fetch the generated report.

report.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class ReportService {
  private apiUrl = 'https://localhost:5001/api/Report';

  constructor(private http: HttpClient) {}

  getReport(reportId: number) {
    return this.http.get(`${this.apiUrl}/GenerateReport?reportId=${reportId}`, { responseType: 'blob' });
  }
}


Step 3. Display Report in Angular Component
Now, create a component to display the generated report (PDF).

report-viewer.component.ts
import { Component } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { ReportService } from './report.service';

@Component({
  selector: 'app-report-viewer',
  templateUrl: './report-viewer.component.html',
  styleUrls: ['./report-viewer.component.css']
})
export class ReportViewerComponent {
  pdfSrc: any;

  constructor(private reportService: ReportService, private sanitizer: DomSanitizer) {}

  loadReport() {
    const reportId = 101; // dynamic ID based on user selection
    this.reportService.getReport(reportId).subscribe((data) => {
      const blob = new Blob([data], { type: 'application/pdf' });
      const url = URL.createObjectURL(blob);
      this.pdfSrc = this.sanitizer.bypassSecurityTrustResourceUrl(url);
    });
  }
}


report-viewer.component.html
<div class="report-container">
  <button (click)="loadReport()" class="btn btn-primary">Generate Report</button>

  <iframe *ngIf="pdfSrc" [src]="pdfSrc" width="100%" height="600px"></iframe>
</div>


Step 4. Style and Integration
You can enhance the user interface by integrating Bootstrap or Angular Material:

npm install bootstrap

In angular.json:
"styles": [
  "node_modules/bootstrap/dist/css/bootstrap.min.css",
  "src/styles.css"
]


Step 5. Dynamic Report Parameters
You can allow users to select filters (like date range, department, or region) and pass them to the API dynamically:
this.reportService.getReportByParams({ startDate, endDate, region });

Your backend can then use these parameters in SQL queries or stored procedures to fetch dynamic data.

Conclusion

By combining Angular’s dynamic frontend capabilities with a .NET backend that interfaces with ActiveX or COM-based report engines, you can:
Generate dynamic reports using real-time database data
Export reports in formats like PDF or Excel
Integrate modern UI controls while preserving legacy ActiveX report compatibility
This hybrid approach enables organizations to modernize their reporting systems without completely discarding older but reliable ActiveX reporting engines.



AngularJS Hosting Europe - HostForLIFE :: Using ASP.NET Core + Angular to Integrate UPS and FedEx APIs for Shipping

clock October 24, 2025 08:00 by author Peter

In the realm of e-commerce today, shipping is crucial. Consumers anticipate accurate and timely delivery. FedEx and UPS are two well-known shipping companies. Creating shipping labels, tracking deliveries, and automatically calculating shipping costs are all made possible by connecting their APIs when developing an ERP, e-commerce, or shipping system. In this tutorial, I will demonstrate how to easily integrate the UPS and FedEx APIs using Angular for the frontend and ASP.NET Core for the backend.

Create Developer Account
UPS:

  • Go to UPS Developer Portal.
  • Sign up for a free account.

Request API access keys. You will get:

  • Access Key
  • Username
  • Password

Note the API endpoints (sandbox and production).

FedEx:

  • Go to FedEx Developer Portal.
  • Sign up for a free developer account.

Request API credentials:

  1. Key
  2. Password
  3. Account Number
  4. Meter Number

Note FedEx sandbox and production URLs.

Backend Setup: ASP.NET Core
We will create APIs in ASP.NET Core to talk to UPS and FedEx.

Step 1. Create ASP.NET Core Project
dotnet new webapi -n ShippingAPI
cd ShippingAPI


Step 2. Add Required Packages
Install HttpClientFactory and Newtonsoft.Json for calling API and parsing response:

dotnet add package Microsoft.Extensions.Http
dotnet add package Newtonsoft.Json


Step 3. Create Model for Shipping Request
Create ShippingRequest.cs:
public class ShippingRequest
{
    public string ServiceType { get; set; }  // e.g. "Ground", "Express"
    public string SenderAddress { get; set; }
    public string ReceiverAddress { get; set; }
    public decimal PackageWeight { get; set; }
    public string PackageDimensions { get; set; }
}

Step 4. Create UPS Service
Create UpsService.cs:
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;

public class UpsService
{
    private readonly HttpClient _httpClient;

    public UpsService(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task<string> CreateShipmentAsync(ShippingRequest request)
    {
        var upsRequest = new
        {
            Shipment = new
            {
                Shipper = new { Address = request.SenderAddress },
                ShipTo = new { Address = request.ReceiverAddress },
                Package = new { Weight = request.PackageWeight }
            }
        };

        var json = JsonConvert.SerializeObject(upsRequest);
        var content = new StringContent(json, Encoding.UTF8, "application/json");

        var response = await _httpClient.PostAsync("https://onlinetools.ups.com/rest/Ship", content);
        return await response.Content.ReadAsStringAsync();
    }
}


Step 5. Create FedEx Service
Create FedExService.cs:
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;

public class FedExService
{
    private readonly HttpClient _httpClient;

    public FedExService(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task<string> CreateShipmentAsync(ShippingRequest request)
    {
        var fedExRequest = new
        {
            RequestedShipment = new
            {
                ShipTimestamp = DateTime.UtcNow,
                Shipper = new { Address = request.SenderAddress },
                Recipient = new { Address = request.ReceiverAddress },
                PackageCount = 1,
                PackageWeight = request.PackageWeight
            }
        };

        var json = JsonConvert.SerializeObject(fedExRequest);
        var content = new StringContent(json, Encoding.UTF8, "application/json");

        var response = await _httpClient.PostAsync("https://apis-sandbox.fedex.com/ship/v1/shipments", content);
        return await response.Content.ReadAsStringAsync();
    }
}

Step 6. Register Services in Program.cs
builder.Services.AddHttpClient<UpsService>();
builder.Services.AddHttpClient<FedExService>();


Step 7. Create Shipping Controller
[ApiController]
[Route("api/[controller]")]
public class ShippingController : ControllerBase
{
    private readonly UpsService _upsService;
    private readonly FedExService _fedExService;

    public ShippingController(UpsService upsService, FedExService fedExService)
    {
        _upsService = upsService;
        _fedExService = fedExService;
    }

    [HttpPost("ups")]
    public async Task<IActionResult> CreateUpsShipment([FromBody] ShippingRequest request)
    {
        var result = await _upsService.CreateShipmentAsync(request);
        return Ok(result);
    }

    [HttpPost("fedex")]
    public async Task<IActionResult> CreateFedExShipment([FromBody] ShippingRequest request)
    {
        var result = await _fedExService.CreateShipmentAsync(request);
        return Ok(result);
    }
}


Frontend Setup: Angular
Step 1. Create Angular Service

ng generate service shipping

shipping.service.ts:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class ShippingService {
  private baseUrl = 'https://localhost:5001/api/shipping';

  constructor(private http: HttpClient) {}

  createUpsShipment(shippingData: any) {
    return this.http.post(`${this.baseUrl}/ups`, shippingData);
  }

  createFedExShipment(shippingData: any) {
    return this.http.post(`${this.baseUrl}/fedex`, shippingData);
  }
}

Step 2. Create an Angular Component
ng generate component shipping

shipping.component.ts:

import { Component } from '@angular/core';
import { ShippingService } from './shipping.service';

@Component({
  selector: 'app-shipping',
  templateUrl: './shipping.component.html'
})
export class ShippingComponent {
  shippingData = {
    serviceType: 'Ground',
    senderAddress: 'Sender Address Here',
    receiverAddress: 'Receiver Address Here',
    packageWeight: 2
  };

  constructor(private shippingService: ShippingService) {}

  createUpsShipment() {
    this.shippingService.createUpsShipment(this.shippingData).subscribe(res => {
      console.log('UPS Response:', res);
    });
  }

  createFedExShipment() {
    this.shippingService.createFedExShipment(this.shippingData).subscribe(res => {
      console.log('FedEx Response:', res);
    });
  }
}

shipping.component.html:
<h3>Create Shipment</h3>
<button (click)="createUpsShipment()">Create UPS Shipment</button>
<button (click)="createFedExShipment()">Create FedEx Shipment</button>


Test Your Integration
Run ASP.NET Core backend: dotnet run
Run Angular frontend: ng serve
Open the Angular app in the browser and click Create UPS Shipment or Create FedEx Shipment.
Check the console for response and verify the shipping label or tracking number returned by UPS/FedEx.

Notes and Tips

  • Always test first in sandbox environment.
  • Keep API keys and passwords secure (never commit to Git).
  • For production, switch to production API URLs.
  • You can extend this integration to track shipments, calculate rates, and print labels.

Conclusion
Integrating UPS and FedEx APIs in your system using ASP.NET Core and Angular helps automate shipping, save time, and reduce errors. Once integrated, you can easily create shipments, track them, and manage shipping cost dynamically. By following this guide step by step, even beginners can implement shipping API integration without much trouble.



AngularJS Hosting Europe - HostForLIFE :: A Comprehensive Guide to Angular Cheatsheets

clock August 15, 2025 08:27 by author Peter

Google created the well-known front-end web framework Angular. With HTML, CSS, and TypeScript, it facilitates the creation of quick, interactive, and organized single-page applications (SPAs). Components, services, routing, and dependency injection are some of the tools that Angular offers to facilitate and organize the development of large-scale online applications.

1. NgModule, or the Angular Module
A module is defined as a container for directives, pipes, services, and components. There is a root module named AppModule in every Angular application.
For instance

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  bootstrap: [AppComponent]
})
export class AppModule { }

Key Point: Modules organize the app into functional sections.

2. Component

Definition: A component controls a part of the user interface. Each component has three parts: HTML template, TypeScript class, and CSS style.

Example
@Component({
  selector: 'app-hello',
  template: '<h1>Hello {{ name }}</h1>'
})
export class HelloComponent {
  name = 'World';
}


Key Point: Components are the basic building blocks of any Angular app.

3. Data Binding
Definition: Data binding connects the data between your class (TypeScript) and the template (HTML).
Types and Examples
      Interpolation: {{ value }}
    Property Binding: [src]="imageUrl"
    Event Binding: (click)="doSomething()"
    Two-way Binding: [(ngModel)]="name"


Key Point: Use FormsModule for two-way binding with ngModel.

4. Directives
Definition: Directives change the behavior or appearance of elements.

Types
Structural Directives: *ngIf, *ngFor
Attribute Directives: [ngClass], [ngStyle]

Example
<p *ngIf="isVisible">This is visible</p>

Key Point: Structural directives change the DOM layout.

5. Services and Dependency Injection

Definition: Services are used to share data or logic across components. Angular uses dependency injection to provide services.

Example
@Injectable()
export class DataService {
  getData() {
    return ['One', 'Two', 'Three'];
  }
}


Key Point: Use services to avoid repeating logic in multiple components.

6. Routing

Definition: Routing is used to navigate between different views or components.

Example
const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutComponent }
];


Key Point: Use <router-outlet> in HTML to display routed views.

7. Lifecycle Hooks
Definition: Hooks let you run code at specific times in a component’s life.
Common Hooks

  • ngOnInit(): Runs after component initializes.
  • ngOnDestroy(): Runs before component is removed.

Example
ngOnInit() {
  console.log('Component loaded');
}


Key Point: Use ngOnInit() to fetch data when the component loads.

8. Pipes
Definition: Pipes transform the data in the template.
Built-in Pipes: date, uppercase, lowercase, currency

Example
<p>{{ today | date }}</p>

Key Point: You can also create custom pipes using @Pipe.

9. Forms

Definition: Angular provides two types of forms:

  • Template-driven (simple, suitable for small apps)
  • Reactive forms (more control, suitable for large apps)


Template-driven Example
<input [(ngModel)]="user.name">

Reactive Example
this.form = new FormGroup({
  name: new FormControl('')
});


Key Point: Import ReactiveFormsModule or FormsModule based on the type of form.

10. HTTPClient
Definition: Angular’s HttpClient is used to make HTTP requests to a backend server.

Example
this.http.get('https://api.example.com/data').subscribe(result => {
  console.log(result);
});


Key Point: Import HttpClientModule and inject HttpClient in the constructor.

11. Event Handling
Definition: Event handling lets you respond to user actions like clicks or input changes.

Example
<button (click)="onClick()">Click Me</button>

onClick() {
  alert('Button clicked!');
}

Key Point: Use event binding syntax (event)="handler()".

12. Template Reference Variable

Definition: Template variables give you a reference to DOM elements in your HTML.

Example
<input #userInput>
<button (click)="log(userInput.value)">Log</button>


Key Point: Template variables start with #.

13. ngFor and ngIf

Definition: Used to display lists or conditionally show/hide elements.

Example
<li *ngFor="let item of items">{{ item }}</li>
<div *ngIf="isLoggedIn">Welcome</div>

Key Point: Use trackBy in ngFor for better performance.

14. @Input and @Output
Definition
    @Input passes data into a component.
    @Output sends data out using EventEmitter.

Example
@Input() title: string;
@Output() clicked = new EventEmitter<void>();


Key Point: Use these to communicate between parent and child components.

15. Angular CLI Commands

Definition: CLI helps you create and manage Angular apps.

Common Commands
    ng new app-name: Create a new app
    ng serve: Run the app locally
    ng generate component name: Create a component
    ng build: Build the app for production


Key Point: CLI automates repetitive tasks.
16. Interceptors
Definition: Interceptors are used to modify HTTP requests or responses globally (for example, adding auth tokens or handling errors).

Example:
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    const token = 'my-token';
    const authReq = req.clone({
      headers: req.headers.set('Authorization', `Bearer ${token}`)
    });
    return next.handle(authReq);
  }
}


Key Point: Register interceptors in providers using { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }.

17. Guards (Route Protection)

Definition: Guards control access to routes based on logic like login status or user roles.

Types: CanActivate, CanDeactivate, CanLoad, Resolve

Example
@Injectable()
export class AuthGuard implements CanActivate {
  canActivate(): boolean {
    return isUserLoggedIn(); // your custom logic
  }
}


Key Point: Attach guards in the route configuration.

18. Lazy Loading

Definition: Lazy loading loads modules only when needed, reducing the initial load time.

Example
const routes: Routes = [
  { path: 'admin', loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule) }
];


Key Point: Use loadChildren in the routing module for lazy loading.
19. Standalone Components (Angular 14+)
Definition: Components that do not need to be declared inside a module. Useful for simpler architecture and micro frontends.

Example
@Component({
  standalone: true,
  selector: 'app-simple',
  template: '<p>Standalone works!</p>',
  imports: [CommonModule]
})
export class SimpleComponent {}


Key Point: Use them for lightweight or isolated features.

20. Environment Files

Definition: Store different settings (like API URLs) for development and production.

Example:
// environment.ts
export const environment = {
  production: false,
  apiUrl: 'http://localhost:3000'
};

Key Point: Use environment.apiUrl in services to avoid hardcoding URLs.

21. TrackBy with ngFor
Definition: Improves rendering performance by identifying items uniquely.

Example
<li *ngFor="let item of items; trackBy: trackById">{{ item.name }}</li>

trackById(index: number, item: any) {
  return item.id;
}


Key Point: Always use trackBy when rendering large lists.

22. Content Projection (ng-content)

Definition: Allows you to insert custom HTML content into a component.

Example
<!-- In reusable component -->
<div class="box">
  <ng-content></ng-content>
</div>

<!-- Usage -->
<app-box>
  <p>This content goes inside the box</p>
</app-box>

Key Point: Use for building reusable UI components like modals and cards.

23. ViewChild and ViewChildren

Definition: Access DOM elements or child components from the class.

Example
@ViewChild('myInput') inputRef: ElementRef;

ngAfterViewInit() {
  console.log(this.inputRef.nativeElement.value);
}


Key Point: Access is available only after ngAfterViewInit().

24. Custom Directive

Definition: Create your own directive to change element behavior.

Example
@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor(el: ElementRef) {
    el.nativeElement.style.backgroundColor = 'yellow';
  }
}


Key Point: Directives add custom behavior to HTML elements.

25. State Management (Basics)

Definition: Managing shared data across components.

Approaches

  • Service with RxJS
  • NgRx (Redux-style)
  • Component Input/Output


Example (RxJS)
private data = new BehaviorSubject<string>('initial');
data$ = this.data.asObservable();


Key Point: Use shared services and Observables to manage app state without tight coupling.

26. Animations

Definition: Angular provides animation support via @angular/animations.

Example
trigger('fadeIn', [
  transition(':enter', [
    style({ opacity: 0 }),
    animate('500ms', style({ opacity: 1 }))
  ])
])

Key Point: Import BrowserAnimationsModule in AppModule to enable animations.

27. Change Detection Strategy

Definition: Angular runs change detection to update the view when data changes. You can control this behavior using strategies.

Types

  • Default: Checks all components.
  • OnPush: Only checks when input changes or events occur.

Example
@Component({
  selector: 'app-sample',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `<p>{{ data }}</p>`
})
export class SampleComponent { }

Key Point: Use OnPush to boost performance in large apps.

28. Error Handling (Global and Local)

Local Example

this.http.get('/data').subscribe({
  next: data => console.log(data),
  error: err => console.error('Error:', err)
});


Global Error Handler


@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
  handleError(error: any) {
    console.error('Global Error:', error);
  }
}


Key Point: Always log and handle errors gracefully.
29. Async Pipe
Definition: Automatically subscribes to Observables in templates and unsubscribes when the component is destroyed.

Example
<p>{{ user$ | async }}</p>

Key Point: Avoid manual subscriptions when possible. Prevents memory leaks.

30. Unsubscribe from Observables
Problem: If you forget to unsubscribe, memory leaks can happen.

Solution
private destroy$ = new Subject<void>();

ngOnDestroy() {
  this.destroy$.next();
  this.destroy$.complete();
}


Key Point: Always unsubscribe from long-living Observables like interval() or HttpClient.

31. Structural Directive with ng-template

Definition: Define a template to render conditionally or repeatedly.

Example
<ng-template [ngIf]="show" [ngIfElse]="elseBlock">Visible</ng-template>
<ng-template #elseBlock>Hidden</ng-template>

Key Point: ng-template helps when you want full control over rendering.

32. Custom Pipe

Definition: Create your own pipe to format data.

Example
@Pipe({ name: 'capitalize' })
export class CapitalizePipe implements PipeTransform {
  transform(value: string): string {
    return value.charAt(0).toUpperCase() + value.slice(1);
  }
}


Key Point: Custom pipes are stateless functions used in templates.

33. Reusable Shared Module
Definition: A module that contains common components, directives, and pipes used across the app.

Example
@NgModule({
  declarations: [HeaderComponent, FooterComponent],
  exports: [HeaderComponent, FooterComponent]
})
export class SharedModule { }


Key Point: Import SharedModule wherever common elements are needed.

34. Feature Modules
Definition: Organize your app into multiple modules for better scalability.
Example: UserModule, AdminModule, AuthModule

Key Point: Each module should focus on a single area of the application.

35. Module Preloading

Definition: Load lazy-loaded modules in the background after the app starts.

Example
RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })

Key Point: Improves user experience by reducing wait time when navigating.

36. Angular Universal (SSR)
Definition: Server-side rendering for Angular apps. Helps with SEO and faster initial loading.

Key Point: Use @nguniversal/express-engine to set up SSR.

37. Web Workers

Definition: Run heavy tasks in a separate thread to keep UI responsive.
Key Point: Use Angular CLI to generate workers:
ng generate web-worker my-worker

38. ViewEncapsulation
Definition: Controls how styles are applied to components.

Types

  • Emulated (default)
  • ShadowDom
  • None


Example
@Component({
  encapsulation: ViewEncapsulation.None
})

Key Point: Choose based on your CSS scoping needs.

39. Testing with Jasmine and Karma

Definition: Angular uses Jasmine for writing tests and Karma for running them.

Example
it('should create the app', () => {
  const fixture = TestBed.createComponent(AppComponent);
  const app = fixture.componentInstance;
  expect(app).toBeTruthy();
});

Key Point: Always write unit tests for components and services.

40. Internationalization (i18n)

Definition: Supports multiple languages in Angular apps.
Key Point: Use Angular’s i18n module or third-party libraries like ngx-translate.

Conclusion

You now have a complete Angular cheatsheet that covers everything from beginner to intermediate and even advanced topics. Mastering Angular means understanding not only how components, services, and routing work but also how to manage performance, structure large projects, test effectively, and write clean, maintainable code.



AngularJS Hosting Europe - HostForLIFE :: Angular Reactive Forms: Real-Time Problem Solving and Dynamic Validation

clock July 24, 2025 08:53 by author Peter

The handling of dynamic form validation in Angular Reactive Forms is described in this article. It illustrates a real-world situation in which validation rules must alter in response to user input, such as requiring a company name for corporations and a PAN number for individuals. According to the article, developers frequently make the error of forgetting to call updateValueAndValidity() after updating or clearing validators, which results in unexpected form behavior. It explains the problem, displays the code that was wrong and fixed, and offers a reusable custom validator for PAN format.


 Overall, with a useful example and real-time bug fixes, this article assists developers in understanding how to implement clear, dynamic validation logic in Angular forms.

Overview
Angular’s Reactive Forms module gives you fine-grained control over form data, structure, and validation. One of the most useful features is dynamically applying validators based on user input or context.

In real-world applications, dynamic validation is essential, for example, requiring a secondary email only if a checkbox is selected, or validating a PAN number only for Indian users.

Scenario

In one of our insurance applications, we had a registration form with the following fields:

  • User Type (Individual / Organization)
  • PAN Number (Mandatory for Individuals)
  • Company Name (Mandatory for Organizations)

The validation was supposed to change dynamically when the user toggles between "Individual" and "Organization".

Initial Implementation
Here’s the basic structure of the Reactive Form:
this.registrationForm = this.fb.group({
  userType: ['Individual'],
  panNumber: [''],
  companyName: ['']
});


In the onUserTypeChange() method, we tried to manually add/remove validators:
onUserTypeChange(userType: string) {
  if (userType === 'Individual') {
    this.registrationForm.get('panNumber')?.setValidators([
      Validators.required,
      this.panValidator
    ]);
    this.registrationForm.get('companyName')?.clearValidators();
  } else {
    this.registrationForm.get('companyName')?.setValidators([
      Validators.required
    ]);
    this.registrationForm.get('panNumber')?.clearValidators();
  }

  // Missing updateValueAndValidity
}

Real-Time Issue Faced
Despite switching user type, the form still showed both fields as invalid/valid incorrectly.

Root Cause
We forgot to call updateValueAndValidity() after changing the validators. As a result, the validation state wasn’t recalculated.

Fix Implemented
We modified the method to:
onUserTypeChange(userType: string) {
  const panControl = this.registrationForm.get('panNumber');
  const companyControl = this.registrationForm.get('companyName');

  if (userType === 'Individual') {
    panControl?.setValidators([Validators.required, this.panValidator]);
    companyControl?.clearValidators();
  } else {
    companyControl?.setValidators([Validators.required]);
    panControl?.clearValidators();
  }

  panControl?.updateValueAndValidity();
  companyControl?.updateValueAndValidity();
}


Also, we triggered onUserTypeChange() on form initialization to ensure it reflects the default selection.

Real-Time PAN Validator

Here’s how the PAN format validator looked:
panValidator(control: AbstractControl): ValidationErrors | null {
  const panRegex = /^[A-Z]{5}[0-9]{4}[A-Z]{1}$/;

  if (control.value && !panRegex.test(control.value)) {
    return { invalidPAN: true };
  }

  return null;
}

Outcome
The dynamic validation works perfectly now

Fields show real-time validation updates
This pattern is reusable across other forms with dynamic sections

Conclusion

Dynamic form validation is a common need in Angular apps. Always remember:

  • Use setValidators() and clearValidators() as needed
  • Call updateValueAndValidity() after updating validators
  • For complex logic, extract reusable custom validators

This simple oversight (not updating the validity) caused hours of confusion in a production bug. But the lesson helped in building better reactive forms in other modules too.



AngularJS Hosting Europe - HostForLIFE :: Communication Between Parent and Child Components: Resolving the Sync Problem

clock July 16, 2025 08:41 by author Peter

Component communication is essential for creating reusable and modular components in Angular. Data is often sent from a parent component to a child component using @Input() and returned using @Output() with an EventEmitter.

The Real Issue
One of our projects involved a parent component passing a selected item ID to a child component via @Input().  The child component used that ID to retrieve and show the details.  However, when the user quickly picked a different item, the kid did not always display the change.  Sometimes it displayed outdated info or didn't update at all.

What Went Wrong
Angular's @Input() only updates when the value changes, but in certain situations (such as when the same ID is passed again after a brief delay), lifecycle hooks like ngOnChanges() failed to detect it. Additionally, ngOnInit() wasn't retriggered on each input change because the child only made one HTTP call.

Solution


We moved the API fetch logic from ngOnInit() to ngOnChanges() and added a proper check for changes:
@Input() itemId!: string;

ngOnChanges(changes: SimpleChanges): void {
  if (changes['itemId'] && changes['itemId'].currentValue) {
    this.loadItemDetails(changes['itemId'].currentValue);
  }
}

loadItemDetails(id: string) {
  this.http.get(`/api/items/${id}`).subscribe(res => {
    this.itemDetails = res;
  });
}


We also added a condition to prevent redundant API calls if the ID hasn’t changed.

Additional Fix
For cases where the same value might be passed again, we manually reset the input before reassigning:
this.selectedItemId = null;
setTimeout(() => this.selectedItemId = item.id, 0);


This trick forces Angular to treat the new input as a different value.

Conclusion
Angular’s @Input() and @Output() work well for component communication, but they don’t always detect subtle changes unless lifecycle hooks are handled properly. Moving logic to ngOnChanges() ensures that child components respond to dynamic data accurately.



AngularJS Hosting Europe - HostForLIFE :: Lazy Loading in Angular: An Issue and Fix in Real Time

clock July 10, 2025 07:49 by author Peter

A common technique for improving performance in large Angular apps is lazy loading. The practice of loading a module only after the user has reached its route is known as lazy loading. This reduces the initial load time of the application. In one of our projects, we had a dashboard module that was loaded slowly. The module worked flawlessly when the app was being used. However, when the user reloaded the browser while on the dashboard route (http://localhost:4200/dashboard), a blank page or 404 error was shown.

Causes of the Issue
Client-side angular routing is used. When you hit refresh, the browser asks the server to fetch that route, but the server is not aware of this.

How Did We Fix It?
We fixed that by instructing the server to divert all requests to index.html so that Angular could handle the routing. In this case, we changed the.htaccess file with the following since we were using an Apache server:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /

  RewriteRule ^index\.html$ - [L]

  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d

  RewriteRule . /index.html [L]

</IfModule>


There is no issue if you use the built-in dev server in Angular CLI, as it takes care of this already. However, the hosting server needs to know for production.

Conclusion

App performance is enhanced by lazy loading, but if the server is not set up correctly, it may result in unforeseen problems. To allow Angular to handle routing, always ensure that your server reroutes unknown routes to index.html.



AngularJS Hosting Europe - HostForLIFE :: Angular Lifecycle Hooks: An Understanding

clock July 1, 2025 08:06 by author Peter

Google developed the open-source Angular frontend framework, which is based on TypeScript. It assists developers in creating scalable, contemporary online applications, particularly Single Page Applications (SPAs), in which content updates dynamically rather than requiring a page reload. By employing components and services to arrange our code, it facilitates efficient and maintainable development. We must first establish a clear understanding of Angular's definition, structure, and component placement before lifecycle hooks make any sense.

AngularJS vs Angular (Modern Angular)

Feature AngularJS Angular (2+)
Language JavaScript TypeScript
Architecture MVC Component-based
Mobile Support Poor Excellent
Performance Slower Faster (AOT, Tree Shaking)
Development Support Discontinued Actively maintained
Ecosystem Classic JS ecosystem RxJS, TypeScript, CLI

Here’s how the high-level angular structure looks.

Angular Element Purpose School App Example
Modules Organize the app into functional areas StudentModule, TeacherModule, AdminModule, and TimetableModule group features into manageable sections.
Components Handle UI and logic for individual features StudentListComponent, AttendanceFormComponent, and ExamResultsComponent power the core screens of the app.
Templates Define the view using Angular-enhanced HTML A dynamic report card template uses *ngFor to loop through subjects and display student scores.
Services Share business logic and data access across components StudentService centralizes logic to fetch, add, or update student records from the backend.
Routing Enable navigation between pages Angular Router handles navigation to /students, /teachers, /results, and /library.
Directives Add dynamic behavior to templates *ngIf="isAbsent" highlights students in red if they’re absent during the attendance check.
Pipes Format output in templates {{ dateOfBirth | date:'longDate' }} formats a birthday date

What is a Component in Angular?

The core of the user interface in Angular is a component. Usually, every screen, button, form, or card is implemented as a component, much like the Common Language Runtime (CLR) components in.NET. A component is the fundamental unit of the user interface (UI) in Angular. It holds the HTML template, CSS styling, and TypeScript logic for a view, which is a section of the screen that it controls.

Structure of a Component
1. Class contains the logic and data for the component using TypeScript. And File Extension: .ts
@Component({
  selector: 'app-product',         // We can use <app-product></app-product> in HTML
  templateUrl: './product.html',   // Uses product.html for UI
  styleUrls: ['./product.css']     // Uses product.css for styles
})
export class ProductComponent {    // This class holds logic like product name, price, etc.
  name = 'T-Shirt';
  price = 499;
}


2. Template defines the user interface (UI layout) using HTML. It displays data from the class using Angular's data binding.File Extension: .html
<!-- product.component.html -->
<h2>{{ productName }}</h2>
<p>Price: ₹{{ price }}</p>

3. Style adds styling (colors, fonts, spacing) specific to this component. File Extension: .css or .scss

/* product.component.css */
h2 {
  color: blue;
  font-weight: bold;
}

p {
  font-size: 16px;
}


Why are components important for Lifecycle Hooks?

Lifecycle hooks are embedded within components. So, unless you understand how components are created, rendered, and destroyed, lifecycle hooks won’t mean much. Here’s the flow.

  • Angular initializes a component.
  • Angular runs specific hooks at each stage of that component's life.
  • We use those hooks to run our own logic at the perfect moment (like fetching data, unsubscribing, or calculating total).

Angular Lifecycle Hooks
Lifecycle hooks in Angular are special methods that get called automatically at specific stages of a component’s life, from creation to destruction. Lifecycle hooks let Angular manage the creation, change detection, and destruction of components. This gives us fine control over how and when code runs.

Lifecycle hooks are built-in functions that Angular calls at different moments during a component’s lifetime, like when it's created, updated, or destroyed.
Why Use Lifecycle Hooks?

We use lifecycle hooks to,

  • Run initial setup code (like fetching data when the component loads)
  • Detect changes in inputs
  • Perform cleanup tasks (like clearing timers or unsubscribing from services)
  • Debug the flow of your component.


Hook Name When Called Purpose Usage Example
constructor() When a component instance is created Basic initialization of class members (no Angular bindings yet) console.log('Constructor')
ngOnChanges(changes: SimpleChanges) When @Input() property changes Respond to input property changes this.loadData(changes['userId'].currentValue);
ngOnInit() Once after the first ngOnChanges() Fetch data, initialize bindings this.getDataFromService();
ngDoCheck() Every change detection run Custom change tracking logic detectManualChange();
ngAfterContentInit() After content projected via <ng-content> is initialized Set up logic dependent on projected content console.log('ng-content loaded')
ngAfterContentChecked() After every check of the content projection Respond to changes in projected content validateProjectedTemplate();
ngAfterViewInit() After the component’s view (and child views) are initialized DOM access, @ViewChild operations this.chart.init(this.chartElement.nativeElement);
ngAfterViewChecked() After every check of the component and child views Update logic if template data changes adjustLayout();
ngOnDestroy() Just before Angular destroys the component Cleanup (unsubscribe, clear interval) subscription.unsubscribe();

Conclusion
Understanding Angular’s architecture is essential for building modern, scalable, and maintainable web applications. This article walked through the foundational blocks of Angular, Components, Component Lifecycle Hooks, which provide precise control over how Angular creates, updates, and destroys components.

 



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in