npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

ngx-st-snack-bar

v19.0.0

Published

- [Overview](#overview) - [Installation](#installation) - [Basic Usage](#basic-usage) - [Methods](#methods) - [Usage Examples](#usage-examples) - [Best Practices](#best-practices)

Readme

Snack Bar Service - Complete Documentation

Table of Contents


Overview

The StSnackBarService provides styled snackbar notifications with four types:

  • Success: Green snackbar for successful operations
  • Warning: Orange snackbar for warnings
  • Info: Blue snackbar for informational messages
  • Error: Red snackbar for errors (longer duration)

Features:

  • Pre-styled Material Design snackbars
  • Automatic positioning (top-right)
  • Automatic dismissal
  • Different durations for different types
  • Material icons included

Installation

npm install ngx-st-snack-bar

Import the module:

import { StSnackBarModule } from 'ngx-st-snack-bar';

@NgModule({
  imports: [StSnackBarModule]
})
export class AppModule { }

Basic Usage

// Component
import { StSnackBarService } from 'ngx-st-snack-bar';

@Component({...})
export class MyComponent {
  constructor(private snackBar: StSnackBarService) {}
  
  save(): void {
    this.api.save().subscribe(
      () => this.snackBar.success('Saved successfully!'),
      () => this.snackBar.error('Failed to save')
    );
  }
}

Methods

success(message: string)

  • Description: Shows a green success snackbar.
  • Duration: 5 seconds
  • Position: Top-right
  • Example:
    this.snackBar.success('User created successfully!');
    this.snackBar.success('Changes saved');
    this.snackBar.success('File uploaded');

warning(message: string)

  • Description: Shows an orange warning snackbar.
  • Duration: 5 seconds
  • Position: Top-right
  • Example:
    this.snackBar.warning('This action cannot be undone');
    this.snackBar.warning('Please review the changes');
    this.snackBar.warning('Storage almost full');

info(message: string)

  • Description: Shows a blue informational snackbar.
  • Duration: 5 seconds
  • Position: Top-right
  • Example:
    this.snackBar.info('New version available');
    this.snackBar.info('5 items selected');
    this.snackBar.info('Syncing in background');

error(message: string)

  • Description: Shows a red error snackbar.
  • Duration: 15 seconds (longer than others)
  • Position: Top-right
  • Example:
    this.snackBar.error('Failed to save data');
    this.snackBar.error('Network connection lost');
    this.snackBar.error('Invalid credentials');

Usage Examples

Example 1: CRUD Operations

// Component
@Component({
  selector: 'app-user-form',
  template: `
    <form [formGroup]="form" (ngSubmit)="save()">
      <!-- Form fields -->
      <button type="submit">Save</button>
      <button type="button" (click)="delete()">Delete</button>
    </form>
  `
})
export class UserFormComponent {
  form = this.fb.group({...});
  
  constructor(
    private fb: FormBuilder,
    private userService: UserService,
    private snackBar: StSnackBarService
  ) {}
  
  save(): void {
    if (this.form.valid) {
      this.userService.save(this.form.value).subscribe(
        () => {
          this.snackBar.success('User saved successfully');
          this.router.navigate(['/users']);
        },
        error => {
          this.snackBar.error('Failed to save user');
        }
      );
    }
  }
  
  delete(): void {
    this.userService.delete(this.user.id).subscribe(
      () => {
        this.snackBar.success('User deleted');
        this.router.navigate(['/users']);
      },
      error => {
        this.snackBar.error('Failed to delete user');
      }
    );
  }
}

Example 2: File Upload

// Component
@Component({
  selector: 'app-file-upload',
  template: `
    <ngx-st-file-drop (onFilesUpload)="uploadFiles($event)">
    </ngx-st-file-drop>
  `
})
export class FileUploadComponent {
  constructor(
    private fileService: FileService,
    private snackBar: StSnackBarService
  ) {}
  
  uploadFiles(files: File[]): void {
    this.snackBar.info('Uploading files...');
    
    this.fileService.upload(files).subscribe(
      response => {
        this.snackBar.success(`${files.length} files uploaded successfully`);
      },
      error => {
        this.snackBar.error('File upload failed');
      }
    );
  }
}

Example 3: Form Validation

// Component
@Component({
  selector: 'app-login',
  template: `
    <form [formGroup]="loginForm" (ngSubmit)="login()">
      <input matInput formControlName="email" placeholder="Email">
      <input matInput type="password" formControlName="password" placeholder="Password">
      <button type="submit">Login</button>
    </form>
  `
})
export class LoginComponent {
  loginForm = this.fb.group({
    email: ['', [Validators.required, Validators.email]],
    password: ['', Validators.required]
  });
  
  constructor(
    private fb: FormBuilder,
    private authService: AuthService,
    private snackBar: StSnackBarService
  ) {}
  
  login(): void {
    if (this.loginForm.invalid) {
      this.snackBar.warning('Please fill in all required fields');
      return;
    }
    
    this.authService.login(this.loginForm.value).subscribe(
      () => {
        this.snackBar.success('Login successful');
        this.router.navigate(['/dashboard']);
      },
      error => {
        if (error.status === 401) {
          this.snackBar.error('Invalid email or password');
        } else {
          this.snackBar.error('Login failed. Please try again');
        }
      }
    );
  }
}

Example 4: Bulk Operations

// Component
@Component({
  selector: 'app-bulk-actions',
  template: `
    <button (click)="deleteSelected()">Delete Selected</button>
    <button (click)="exportSelected()">Export Selected</button>
  `
})
export class BulkActionsComponent {
  selectedItems = [1, 2, 3];
  
  constructor(
    private itemService: ItemService,
    private snackBar: StSnackBarService
  ) {}
  
  deleteSelected(): void {
    if (this.selectedItems.length === 0) {
      this.snackBar.warning('No items selected');
      return;
    }
    
    this.snackBar.info(`Deleting ${this.selectedItems.length} items...`);
    
    this.itemService.bulkDelete(this.selectedItems).subscribe(
      () => {
        this.snackBar.success(`${this.selectedItems.length} items deleted`);
        this.selectedItems = [];
      },
      error => {
        this.snackBar.error('Failed to delete items');
      }
    );
  }
  
  exportSelected(): void {
    if (this.selectedItems.length === 0) {
      this.snackBar.warning('No items selected for export');
      return;
    }
    
    this.snackBar.info('Preparing export...');
    
    this.itemService.export(this.selectedItems).subscribe(
      () => {
        this.snackBar.success('Export completed');
      },
      error => {
        this.snackBar.error('Export failed');
      }
    );
  }
}

Example 5: Copy to Clipboard

// Component
@Component({
  selector: 'app-copy-button',
  template: `
    <button (click)="copyToClipboard()">
      <mat-icon>content_copy</mat-icon>
      Copy
    </button>
  `
})
export class CopyButtonComponent {
  @Input() text: string;
  
  constructor(private snackBar: StSnackBarService) {}
  
  copyToClipboard(): void {
    navigator.clipboard.writeText(this.text).then(
      () => {
        this.snackBar.success('Copied to clipboard');
      },
      () => {
        this.snackBar.error('Failed to copy');
      }
    );
  }
}

Example 6: Network Status

// Service
@Injectable({
  providedIn: 'root'
})
export class NetworkService {
  constructor(private snackBar: StSnackBarService) {
    this.monitorConnection();
  }
  
  private monitorConnection(): void {
    window.addEventListener('online', () => {
      this.snackBar.success('Connection restored');
    });
    
    window.addEventListener('offline', () => {
      this.snackBar.error('No internet connection');
    });
  }
}

Example 7: API Error Handler

// Interceptor
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
  constructor(private snackBar: StSnackBarService) {}
  
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
      catchError((error: HttpErrorResponse) => {
        let message = 'An error occurred';
        
        switch (error.status) {
          case 400:
            message = 'Invalid request';
            break;
          case 401:
            message = 'Unauthorized';
            break;
          case 403:
            message = 'Access denied';
            break;
          case 404:
            message = 'Resource not found';
            break;
          case 500:
            message = 'Server error';
            break;
        }
        
        this.snackBar.error(message);
        return throwError(() => error);
      })
    );
  }
}

Example 8: Settings Save

// Component
@Component({
  selector: 'app-settings',
  template: `
    <form [formGroup]="settingsForm">
      <!-- Settings fields -->
      <button (click)="save()">Save Settings</button>
      <button (click)="reset()">Reset to Defaults</button>
    </form>
  `
})
export class SettingsComponent {
  settingsForm = this.fb.group({...});
  
  constructor(
    private fb: FormBuilder,
    private settingsService: SettingsService,
    private snackBar: StSnackBarService
  ) {}
  
  save(): void {
    this.settingsService.save(this.settingsForm.value).subscribe(
      () => {
        this.snackBar.success('Settings saved successfully');
      },
      error => {
        this.snackBar.error('Failed to save settings');
      }
    );
  }
  
  reset(): void {
    this.settingsService.resetToDefaults().subscribe(
      defaults => {
        this.settingsForm.patchValue(defaults);
        this.snackBar.info('Settings reset to defaults');
      },
      error => {
        this.snackBar.error('Failed to reset settings');
      }
    );
  }
}

Best Practices

  1. Use appropriate message types:

    // Success - for completed operations
    this.snackBar.success('User created');
       
    // Warning - for cautions
    this.snackBar.warning('This cannot be undone');
       
    // Info - for information
    this.snackBar.info('5 items selected');
       
    // Error - for failures
    this.snackBar.error('Save failed');
  2. Keep messages concise:

    this.snackBar.success('Saved');  // Good
    this.snackBar.success('Your changes have been successfully saved to the database');  // Too long
  3. Use action-specific messages:

    this.snackBar.success('User created');  // Good
    this.snackBar.success('Success');  // Less informative
  4. Handle errors appropriately:

    this.api.save().subscribe(
      () => this.snackBar.success('Saved'),
      error => {
        if (error.status === 403) {
          this.snackBar.error('Access denied');
        } else {
          this.snackBar.error('Failed to save');
        }
      }
    );
  5. Don't overuse snackbars:

    // Good - notify on important actions
    this.snackBar.success('Order placed');
       
    // Bad - notifying every small interaction
    this.snackBar.info('Button clicked');  // Don't do this

Configuration

Default configuration:

  • Position: Top-right
  • Success duration: 5 seconds
  • Warning duration: 5 seconds
  • Info duration: 5 seconds
  • Error duration: 15 seconds (longer for errors)

Snackbar Types

Success (Green)

  • Icon: Check circle
  • Use for: Successful operations, confirmations
  • Examples: "Saved", "Created", "Deleted", "Updated"

Warning (Orange)

  • Icon: Warning
  • Use for: Cautions, confirmations needed
  • Examples: "Cannot undo", "Low storage", "Review required"

Info (Blue)

  • Icon: Info
  • Use for: Information, status updates
  • Examples: "5 selected", "Syncing", "Processing"

Error (Red)

  • Icon: Error
  • Use for: Failures, errors
  • Examples: "Save failed", "Connection lost", "Invalid input"
  • Note: Stays visible longer (15 seconds)

Common Use Cases

  1. CRUD Operations: Success/error feedback
  2. Form Validation: Warning messages
  3. File Operations: Upload/download status
  4. Network Status: Connection changes
  5. Clipboard Operations: Copy confirmation
  6. Bulk Actions: Operation progress
  7. Settings: Save confirmation

This documentation covers all methods and usage patterns for the Snack Bar Service.