Skip to content

evicio1/ngx-mat-progress-bar

Repository files navigation

NgxMatProgressBar

npm version MIT License Angular npm downloads

A modern Angular standalone library that provides a global progress bar component using Angular Material Design. Built for the latest Angular with signals, functional interceptors, and standalone components. Perfect replacement for ngx-progressbar with configurable options and smart HTTP request batching.

🚨 Breaking Change Notice (v20.1.0): The provider API has been simplified! provideNgxMatProgressBar and provideNgxMatProgressBarOptions are now merged into a single provideNgxMatProgressBar() function. See Migration Guide below.

🎯 Key Features

  • πŸš€ Modern Angular - Standalone components, signals, functional interceptors
  • 🎨 Pure Angular Material - Direct use of mat-progress-bar without wrapper components
  • ⚑ Functional HTTP Interceptor - Latest Angular patterns for request tracking
  • πŸ’« Signal-Based Service - Reactive state management with Angular signals
  • πŸŽ›οΈ Smart HTTP Batching - Prevents flickering during multiple simultaneous requests
  • βš™οΈ Configurable Options - Customizable debounce timing and behavior settings
  • 🧭 Router Navigation Tracking - Automatic progress indication during route navigation
  • πŸ”§ Full Material API - Complete access to all Material progress bar features
  • 🎨 User Control - You style and position the progress bar as needed
  • β™Ώ Native Accessibility - Built-in Material Design accessibility
  • πŸ“± Material Responsive - Standard Material Design responsiveness
  • πŸ”„ Core Focus - Only HTTP interception and service logic
  • 🚫 No Wrappers - Clean, minimal component structure

πŸ“¦ Installation

npm install ngx-mat-progress-bar

Peer Dependencies

Make sure you have the required peer dependencies installed:

npm install @angular/material @angular/cdk

πŸš€ Quick Start

1. Setup Providers

import { bootstrapApplication } from '@angular/platform-browser';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { 
  provideNgxMatProgressBar, 
  httpProgressInterceptor
} from 'ngx-mat-progress-bar';

bootstrapApplication(AppComponent, {
  providers: [
    provideHttpClient(
      withInterceptors([httpProgressInterceptor])
    ),
    // Single provider for all configuration
    provideNgxMatProgressBar({
      // UI Configuration
      color: 'primary',
      mode: 'indeterminate',
      
      // Behavioral Options  
      hideDelay: 300,
      minDisplayTime: 200,
      enableSmartBatching: true,
      enableDebugLogs: false
    })
  ]
});

2. Add the Component to Your Template

<!-- Style and position as needed -->
<div class="progress-wrapper">
  <ngx-mat-progress-bar></ngx-mat-progress-bar>
</div>

<!-- Your app content -->
<router-outlet></router-outlet>
/* Example: Fixed top progress bar */
.progress-wrapper {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  height: 4px;
}

3. Use the Service (with Signals)

import { Component, signal, computed } from '@angular/core';
import { NgxMatProgressBarService } from 'ngx-mat-progress-bar';

@Component({
  // ...
})
export class MyComponent {
  private readonly _isWorking = signal(false);

  // Access reactive signals
  readonly isLoading = computed(() => this.progressBar.isLoading());
  readonly activeRequests = computed(() => this.progressBar.activeRequests());

  constructor(private progressBar: NgxMatProgressBarService) {}

  startLoading() {
    this.progressBar.start();
  }

  setProgress(value: number) {
    this.progressBar.set(value); // 0-100
  }

  completeLoading() {
    this.progressBar.complete();
  }
}

πŸ› οΈ Configuration Options

Smart HTTP Request Batching

The library intelligently handles multiple simultaneous HTTP requests to prevent progress bar flickering:

// Single, comprehensive configuration
provideNgxMatProgressBar({
  // UI Settings
  color: 'primary',
  mode: 'indeterminate',
  
  // Behavioral Settings
  hideDelay: 500,           // Wait 500ms before hiding after requests complete
  minDisplayTime: 300,      // Show for at least 300ms to prevent flashing
  enableSmartBatching: true, // Group overlapping requests (recommended)
  enableDebugLogs: true     // Enable console logging for development
});

// Or configure at runtime
this.progressBar.configureOptions({
  hideDelay: 1000,
  enableDebugLogs: true
});

Configuration Interface

interface NgxMatProgressBarConfiguration {
  // UI Configuration
  color?: 'primary' | 'accent' | 'warn';
  mode?: 'determinate' | 'indeterminate' | 'buffer' | 'query';
  value?: number;           // 0-100
  bufferValue?: number;     // 0-100
  visible?: boolean;        // Initial visibility
  
  // Behavioral Options
  hideDelay?: number;           // Delay before hiding (default: 300ms)
  minDisplayTime?: number;      // Minimum display time (default: 200ms)  
  enableSmartBatching?: boolean; // Smart HTTP batching (default: true)
  enableDebugLogs?: boolean;    // Debug console logs (default: false)
}

πŸ“– API Reference

NgxMatProgressBarService

Methods

Method Description Parameters
start() Start the progress bar None
complete() Complete the progress bar with animation None
set(value) Set progress value value: number (0-100)
inc(amount) Increment progress value amount: number (default: 5)
reset() Reset progress bar None
configureOptions(options) Update configuration options options: NgxMatProgressBarOptions
getOptions() Get current configuration Returns NgxMatProgressBarOptions

Signals

Signal Description Type
config() Current configuration Signal<NgxMatProgressBarConfig>
isLoading() Loading state Signal<boolean>
activeRequests() Number of active requests Signal<number>
isVisible() Visibility state Signal<boolean>
isNavigating() Router navigation state Signal<boolean>

Progress Bar Configuration

interface NgxMatProgressBarConfig {
  color?: 'primary' | 'accent' | 'warn';
  mode?: 'determinate' | 'indeterminate' | 'buffer' | 'query';
  value?: number;           // 0-100
  bufferValue?: number;     // 0-100
  visible?: boolean;
}

πŸ’‘ Usage Examples

Basic Usage

@Component({
  template: `
    <div class="progress-wrapper">
      <ngx-mat-progress-bar></ngx-mat-progress-bar>
    </div>
    <button (click)="doWork()">Start Work</button>
  `,
  styles: [`
    .progress-wrapper {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      z-index: 1000;
      height: 4px;
    }
  `]
})
export class AppComponent {
  constructor(private progressBar: NgxMatProgressBarService) {}

  async doWork() {
    this.progressBar.start();

    try {
      await this.someAsyncWork();
      this.progressBar.complete();
    } catch (error) {
      this.progressBar.reset();
    }
  }
}

Multiple HTTP Requests (Dashboard Loading)

export class DashboardComponent {
  constructor(
    private progressBar: NgxMatProgressBarService,
    private http: HttpClient
  ) {
    // Configure for dashboard with multiple API calls
    this.progressBar.configureOptions({
      hideDelay: 400,           // Wait for potential additional requests
      minDisplayTime: 250,      // Ensure users see loading feedback
      enableSmartBatching: true // Essential for smooth UX
    });
  }

  async loadDashboard() {
    // These HTTP requests will be automatically batched
    // Shows one smooth progress bar instead of flickering
    const user$ = this.http.get('/api/user');
    const analytics$ = this.http.get('/api/analytics');
    const notifications$ = this.http.get('/api/notifications');

    await forkJoin([user$, analytics$, notifications$]).toPromise();
    // Progress bar automatically hides after all requests complete
  }
}

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

MIT License Summary

  • βœ… Commercial use
  • βœ… Modification
  • βœ… Distribution
  • βœ… Private use
  • ❌ Liability
  • ❌ Warranty

πŸ”„ Migration from v20.0.x to v20.1.x

Breaking Change: Merged Provider API

In v20.1.0, we simplified the provider API by merging two functions into one for better developer experience.

Before (v20.0.x):

// Old approach - two separate provider functions
providers: [
  provideNgxMatProgressBar({ color: 'primary', mode: 'indeterminate' }),
  provideNgxMatProgressBarOptions({ hideDelay: 300, enableDebugLogs: true })
]

After (v20.1.x):

// New approach - single unified provider function
providers: [
  provideNgxMatProgressBar({
    color: 'primary',
    mode: 'indeterminate', 
    hideDelay: 300,
    enableDebugLogs: true
  })
]

Migration Steps:

  1. Combine provider calls - Merge configuration objects from both providers into one
  2. Remove duplicate import - Only import provideNgxMatProgressBar
  3. Update configuration - All options now go in the same config object

The new API is cleaner and follows Angular ecosystem patterns better!

οΏ½πŸ”— Links


Made with ❀️ for the Angular community

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages