I have a Notification component that's used to show notifications at the top of the screen. I want to have these notifications fade in and out. The NotificationService
has an array of notifications. When a new notification is added, a timer is set via setTimeout
that will remove the notification after 5 seconds.
The notifications appear and disappear correctly, but the fade animation is only working on the :enter
transition, when the notification appears. When the notification is removed, it simply disappears without a fade animation.
Any idea what I'm doing wrong?
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);
}
}
You should put the @fade
on the parent element (<app-notification>
).
That element is responsible for creating / destroying each notification and as it doesn’t know about the animation on its child, it just removes it before any animation can happen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With