Create a kendo notification service reusable for angular
- User
Create a kendo notification service reusable for angular
- Assistant
Create a kendo notification service reusable for angular
Creating a reusable Kendo UI Notification service for Angular can help you manage notifications consistently across your application. This guide will walk you through setting up Kendo UI for Angular, creating a Notification service, and using it in your Angular components.
Angular Project: Ensure you have an Angular project set up. If not, you can create one using the Angular CLI:
ng new kendo-notification-app
cd kendo-notification-app
Kendo UI for Angular License: Kendo UI for Angular requires a commercial license. If you don’t have one, you can get a free trial.
Use npm to install the necessary Kendo UI packages. For notifications, we'll use the @progress/kendo-angular-notification package along with @progress/kendo-angular-common and @progress/kendo-angular-l10n for localization support.
npm install --save @progress/kendo-angular-notification @progress/kendo-angular-common @progress/kendo-angular-l10n @angular/animations
Kendo UI for Angular relies on Angular Animations. Ensure that BrowserAnimationsModule is imported in your application.
Open your main module file (usually app.module.ts) and import the necessary Kendo UI modules.
// app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NotificationModule } from '@progress/kendo-angular-notification';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent,
// ... other components
],
imports: [
BrowserModule,
BrowserAnimationsModule, // Required for Kendo UI animations
NotificationModule, // Kendo Notification Module
// ... other modules
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Create a new Angular service that wraps the Kendo Notification functionality. This service will be responsible for displaying notifications from anywhere in your application.
Generate a new service using Angular CLI:
ng generate service services/notification
This will create notification.service.ts in the src/app/services directory.
Here's how you can implement the Notification service:
// notification.service.ts
import { Injectable, Injector, ApplicationRef, ComponentFactoryResolver, EmbeddedViewRef, ComponentRef } from '@angular/core';
import { NotificationService as KendoNotificationService, NotificationSettings } from '@progress/kendo-angular-notification';
@Injectable({
providedIn: 'root'
})
export class NotificationService {
constructor(private kendoNotification: KendoNotificationService) { }
/**
* Shows a success notification
* @param message The message to display
* @param title (Optional) The title of the notification
*/
showSuccess(message: string, title?: string): void {
this.kendoNotification.show({
content: message,
cssClass: 'notification-success',
animation: { type: 'slide', duration: 400 },
position: { horizontal: 'right', vertical: 'top' },
type: { style: 'success', icon: true },
title: title || 'Success'
});
}
/**
* Shows an error notification
* @param message The message to display
* @param title (Optional) The title of the notification
*/
showError(message: string, title?: string): void {
this.kendoNotification.show({
content: message,
cssClass: 'notification-error',
animation: { type: 'slide', duration: 400 },
position: { horizontal: 'right', vertical: 'top' },
type: { style: 'error', icon: true },
title: title || 'Error'
});
}
/**
* Shows an info notification
* @param message The message to display
* @param title (Optional) The title of the notification
*/
showInfo(message: string, title?: string): void {
this.kendoNotification.show({
content: message,
cssClass: 'notification-info',
animation: { type: 'slide', duration: 400 },
position: { horizontal: 'right', vertical: 'top' },
type: { style: 'info', icon: true },
title: title || 'Information'
});
}
/**
* Shows a warning notification
* @param message The message to display
* @param title (Optional) The title of the notification
*/
showWarning(message: string, title?: string): void {
this.kendoNotification.show({
content: message,
cssClass: 'notification-warning',
animation: { type: 'slide', duration: 400 },
position: { horizontal: 'right', vertical: 'top' },
type: { style: 'warning', icon: true },
title: title || 'Warning'
});
}
/**
* General method to show notification with custom settings
* @param settings NotificationSettings object
*/
show(settings: NotificationSettings): void {
this.kendoNotification.show(settings);
}
/**
* Closes all notifications
*/
close(): void {
this.kendoNotification.hide();
}
}
Explanation:
Import Statements: Import necessary modules and services from Kendo UI and Angular.
Injectable Service: The service is provided in the root, making it accessible throughout the application.
Constructor: Inject Kendo's NotificationService to leverage its show and hide methods.
Notification Methods: Define methods like showSuccess, showError, showInfo, and showWarning for different types of notifications. Each method configures the notification's appearance and behavior.
General Show Method: A show method that accepts a NotificationSettings object for more customized notifications.
Close Method: A method to close/hide all notifications.
Note: Ensure that CSS classes (notification-success, notification-error, etc.) are defined in your global styles if you want to customize the appearance.
Kendo UI's Notification component requires a container in your application, typically placed in the AppComponent.
<!-- app.component.html -->
<kendo-notification></kendo-notification>
<router-outlet></router-outlet>
Explanation: Adding <kendo-notification></kendo-notification> in your AppComponent template ensures that the notification container is available globally, allowing the NotificationService to display notifications from anywhere.
Alternatively, you can create a separate container component for notifications if you prefer more control, but for simplicity, integrating it into AppComponent works well.
Now that the NotificationService is set up, you can inject it into any Angular component and use its methods to display notifications.
Let's create a sample component that uses the NotificationService.
ng generate component components/sample
// sample.component.ts
import { Component } from '@angular/core';
import { NotificationService } from '../../services/notification.service';
@Component({
selector: 'app-sample',
templateUrl: './sample.component.html',
styles: []
})
export class SampleComponent {
constructor(private notificationService: NotificationService) { }
onSuccess() {
this.notificationService.showSuccess('Operation completed successfully!', 'Success');
}
onError() {
this.notificationService.showError('An error occurred while processing.', 'Error');
}
onInfo() {
this.notificationService.showInfo('This is some information for you.', 'Information');
}
onWarning() {
this.notificationService.showWarning('This is a warning message.', 'Warning');
}
}
<!-- sample.component.html -->
<div class="button-group">
<button (click)="onSuccess()" class="btn btn-success">Show Success</button>
<button (click)="onError()" class="btn btn-danger">Show Error</button>
<button (click)="onInfo()" class="btn btn-info">Show Info</button>
<button (click)="onWarning()" class="btn btn-warning">Show Warning</button>
</div>
Explanation:
Import NotificationService: Import and inject the NotificationService into the component.
Define Methods: Create methods (onSuccess, onError, etc.) that call the corresponding NotificationService methods with appropriate messages and titles.
Template: Add buttons in the template that trigger these methods when clicked.
Ensure that the SampleComponent is declared in your AppModule or the relevant feature module and added to the application’s routing or included in a template to render it.
You can customize the appearance of your notifications using CSS. Kendo UI adds default styles, but you can override them as needed.
/* styles.css */
.notification-success {
background-color: #28a745; /* Green */
color: white;
}
.notification-error {
background-color: #dc3545; /* Red */
color: white;
}
.notification-info {
background-color: #17a2b8; /* Blue */
color: white;
}
.notification-warning {
background-color: #ffc107; /* Yellow */
color: black;
}
Explanation: Define CSS classes to customize the look of different notification types. Ensure these styles are included in your global styles (styles.css) or relevant component styles.
Testing: Run your Angular application and navigate to the SampleComponent. Click the buttons to see the notifications in action.
ng serve
Responsive Positioning: Adjust the position settings in the NotificationService methods if you want notifications to appear in different parts of the screen.
Advanced Features: Explore Kendo UI Notification options like auto-hide duration, stacking, and templates for more advanced use cases. Refer to the Kendo UI for Angular Notification Documentation for more details.
For convenience, here's a summary of the key files involved in this setup.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NotificationModule } from '@progress/kendo-angular-notification';
import { AppComponent } from './app.component';
import { SampleComponent } from './components/sample/sample.component';
@NgModule({
declarations: [
AppComponent,
SampleComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
NotificationModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
(As defined in Step 3)
<kendo-notification></kendo-notification>
<app-sample></app-sample>
(As defined in Step 5)
(As defined in Step 5)
(As defined in Step 6)
By following these steps, you've created a reusable Kendo UI Notification service for your Angular application. This service simplifies managing notifications across different components, ensuring consistency and reducing boilerplate code. You can further enhance this service by adding more customization options, handling different notification lifecycles, or integrating with other services as needed.
References:
Not yet included in a published release.