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-barImport 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
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');Keep messages concise:
this.snackBar.success('Saved'); // Good this.snackBar.success('Your changes have been successfully saved to the database'); // Too longUse action-specific messages:
this.snackBar.success('User created'); // Good this.snackBar.success('Success'); // Less informativeHandle 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'); } } );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
- CRUD Operations: Success/error feedback
- Form Validation: Warning messages
- File Operations: Upload/download status
- Network Status: Connection changes
- Clipboard Operations: Copy confirmation
- Bulk Actions: Operation progress
- Settings: Save confirmation
This documentation covers all methods and usage patterns for the Snack Bar Service.
