Для использования библиотеки Noty в проекте Angular необходимо сначала установить её через npm:
npm install noty --save
После установки требуется подключить стили Noty в глобальные стили
приложения. В Angular это делается через файл
angular.json:
"styles": [
"src/styles.css",
"node_modules/noty/lib/noty.css",
"node_modules/noty/lib/themes/mint.css"
],
"scripts": [
"node_modules/noty/lib/noty.min.js"
]
Выбор темы (mint, metroui,
relax, sunset, nest) влияет на
визуальный стиль уведомлений.
Noty можно использовать в Angular как обычную JS-библиотеку, импортируя её в компонент:
import { Component } from '@angular/core';
import Noty from 'noty';
@Component({
selector: 'app-notifications',
templateUrl: './notifications.component.html'
})
export class NotificationsComponent {
showSuccess() {
new Noty({
text: 'Операция успешно выполнена',
type: 'success',
timeout: 3000,
progressBar: true,
layout: 'topRight'
}).show();
}
showError() {
new Noty({
text: 'Произошла ошибка',
type: 'error',
timeout: 5000,
layout: 'topRight',
theme: 'sunset'
}).show();
}
}
Ключевые параметры:
text – текст уведомления.type – тип уведомления: alert,
success, warning, error,
information.timeout – время автозакрытия в миллисекундах. Если не
указано, уведомление остаётся до ручного закрытия.layout – расположение на экране (top,
topLeft, topRight, bottom,
bottomLeft, bottomRight,
center).theme – визуальная тема уведомления.progressBar – отображение индикатора времени до
закрытия.Для упрощения работы с Noty в Angular рекомендуется создать сервис. Он инкапсулирует логику уведомлений и делает код компонентов чище.
import { Injectable } from '@angular/core';
import Noty from 'noty';
@Injectable({
providedIn: 'root'
})
export class NotificationService {
private createNotification(text: string, type: Noty.Type, timeout = 3000) {
new Noty({
text,
type,
timeout,
layout: 'topRight',
progressBar: true,
theme: 'mint'
}).show();
}
success(message: string) {
this.createNotification(message, 'success');
}
error(message: string) {
this.createNotification(message, 'error', 5000);
}
warning(message: string) {
this.createNotification(message, 'warning', 4000);
}
info(message: string) {
this.createNotification(message, 'information', 3000);
}
}
Теперь в компоненте достаточно вызвать метод сервиса:
constructor(private notificationService: NotificationService) {}
submitForm() {
// логика формы
this.notificationService.success('Форма успешно отправлена');
}
1. Callback-функции
Noty поддерживает хуки жизненного цикла уведомлений:
new Noty({
text: 'Сообщение с коллбэком',
type: 'information',
callbacks: {
onShow: () => console.log('Показано уведомление'),
onClose: () => console.log('Уведомление закрыто')
}
}).show();
2. Пользовательские кнопки
Можно добавлять кнопки для действий:
new Noty({
text: 'Вы хотите удалить запись?',
type: 'alert',
layout: 'center',
modal: true,
buttons: [
Noty.button('Да', 'btn btn-success', () => { console.log('Удалено'); }),
Noty.button('Нет', 'btn btn-error', () => { console.log('Отменено'); })
]
}).show();
3. Настройка анимаций
Noty поддерживает кастомные анимации с помощью CSS или встроенных эффектов:
new Noty({
text: 'С анимацией',
type: 'success',
animation: {
open: 'animated bounceInRight',
close: 'animated bounceOutRight'
}
}).show();
Для этого можно использовать библиотеку animate.css
совместно с Angular.
В Angular удобно использовать Noty вместе с потоками данных:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
import Noty from 'noty';
@Injectable({ providedIn: 'root' })
export class NotificationStreamService {
private notificationSubject = new Subject<{ message: string; type: Noty.Type }>();
notifications$ = this.notificationSubject.asObservable();
push(message: string, type: Noty.Type = 'information') {
this.notificationSubject.next({ message, type });
}
constructor() {
this.notifications$.subscribe(({ message, type }) => {
new Noty({
text: message,
type,
timeout: 3000,
layout: 'topRight',
progressBar: true,
theme: 'mint'
}).show();
});
}
}
Такой подход позволяет централизованно управлять уведомлениями из любого места приложения.
Noty предоставляет метод Noty.overrideDefaults() для
глобальной настройки:
Noty.overrideDefaults({
layout: 'topRight',
theme: 'mint',
timeout: 4000,
progressBar: true
});
После этого все уведомления по умолчанию будут использовать эти параметры, что удобно для стандартизации UI.
modal: true для блокировки фона.