让动画在 Angular 6 组件中不起作用

Joe*_*rdi 6 javascript typescript angular

我有一个通知组件,用于在屏幕顶部显示通知。我想让这些通知淡入淡出。的NotificationService具有通知的阵列。添加新通知时setTimeout,会设置一个计时器,通过该计时器将在 5 秒后删除通知。

通知正确显示和消失,但当通知出现时,淡入淡出动画仅适用于:enter过渡。当通知被移除时,它只会消失而没有淡入淡出动画。

知道我做错了什么吗?

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 }))])
    ])
  ]
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

app.component.html

<div id="notification-container">
  <app-notification *ngFor="let notification of notifications" [notification]="notification"></app-notification>
</div>
Run Code Online (Sandbox Code Playgroud)

app.component.ts

  get notifications() {
    return this.notificationService.notifications;
  }
Run Code Online (Sandbox Code Playgroud)

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*per 7

您应该将@fade放在父元素 ( <app-notification>) 上。

该元素负责创建/销毁每个通知,并且由于它不知道其子项上的动画,它只是在任何动画发生之前将其删除。

  • 谢谢!我能够使用这个想法让它工作,但我必须做出另一个改变。我想知道你是否知道为什么我必须做出这个改变。当我将“@fade”直接应用于“&lt;app-notification&gt;”时,它没有动画。但我将“&lt;app-notification&gt;”包装在“&lt;div&gt;”中,然后它就起作用了。知道为什么吗? (2认同)
  • @JoeAttardi 可能是因为默认情况下组件主机没有 `display` css 属性值。添加`:host { display: block; 组件 css 中的 }` 将设置其显示并可能使动画正常工作......以验证 (2认同)