I've implemented a Notification feature using a Notification component that displays notifications at the top of the screen. The goal is to make these notifications fade in and out smoothly. In my NotificationService
, there's an array that holds all the notifications. Whenever a new notification is added, a timer is set using setTimeout
to remove the notification after 5 seconds.
The notifications are appearing and disappearing as expected, but I'm facing an issue with the fade animation. The fade animation only works when the notification enters (":enter" transition), but when it leaves, the notification simply disappears without any fading effect.
Can anyone spot what might be causing this behavior?
notification.component.ts
:
animations: [
trigger('fade', [
transition(':enter', [style({ opacity: 0 }), animate('0.2s', style({ opacity: 1 }))]),
transition(':leave', [style({ opacity: 1 }), animate('0.2s', style({ opacity: 0 }))])
])
]
notification.component.html
:
<div @fade class="notification notification-{{ notification.theme }}">
<div class="icon"><fa-icon [icon]="icons[notification.theme]"></fa-icon></div>
<div class="message">{{ notification.message }}</div>
<div class="close"><fa-icon (click)="closeButtonClicked()" [icon]="icons.close"></fa-icon></div>
</div>
app.component.html
:
<div id="notification-container">
<app-notification *ngFor="let notification of notifications" [notification]="notification"></app-notification>
</div>
app.component.ts
:
get notifications() {
return this.notificationService.notifications;
}
notification.service.ts
:
export class NotificationService {
notifications: Notification[] = [];
showNotification(notificationToShow: Notification) {
this.notifications = [notificationToShow, ...this.notifications];
setTimeout(() => this.removeNotification(notificationToShow), 5000);
}
removeNotification(notificationToRemove: Notification) {
this.notifications = this.notifications.filter(notification => notification !== notificationToRemove);
}
}