如何在mat-tab-group中更改Angular的过渡效果?

3
Angular的mat-tab-group已经包含了每个mat-tab的动画效果。但是给定的动画效果相当烦人,因此我想使用不同的动画效果。我已经从别人那里获得了一个fadeinfadeout的动画效果。链接
export const fadeAnimation = trigger('fadeAnimation', [
  // The '* => *' will trigger the animation to change between any two states
  transition('* => *', [
    // The query function has three params.
    // First is the event, so this will apply on entering or when the element is added to the DOM.
    // Second is a list of styles or animations to apply.
    // Third we add a config object with optional set to true, this is to signal
    // angular that the animation may not apply as it may or may not be in the DOM.
    query(
      ':enter',
      [style({ opacity: 0 })],
      { optional: true }
    ),
    query(
      ':leave',
      // here we apply a style and use the animate function to apply the style over 0.3 seconds
      [style({ opacity: 1 }), animate('0.3s', style({ opacity: 0 }))],
      { optional: true }
    ),
    query(
      ':enter',
      [style({ opacity: 0 }), animate('0.3s', style({ opacity: 1 }))],
      { optional: true }
    )
  ])
]);

尝试像这样应用:
<mat-tab-group animationDuration="0ms">
  <mat-tab label="First"> 
      <div [@fadeAnimation]="'enter'">
           Content 1 
      </div>
  </mat-tab>
  <mat-tab label="Second"> Content 2 </mat-tab>
  <mat-tab label="Third"> Content 3 </mat-tab>
</mat-tab-group>

执行失败。有没有提示如何正确应用它?

根据@ysf的建议更新了示例。


angular-material目前还不支持覆盖默认动画,这里是问题链接,然而mat-tab-group允许控制动画的持续时间,如此处所述,但这并不是你想要的。为了应用自定义动画,您需要在选项卡组上禁用Angular动画并实现自己的CSS动画。 - ysf
我也看了一下默认选项卡动画的源代码(在此处:https://github.com/angular/components/blob/master/src/material/tabs/tabs-animations.ts),默认动画沿着X轴平移一个选项卡。这可能会让你实现自定义所需的动画变得非常具有挑战性(但并非不可能)。 - ysf
我已经根据您的第一条评论更新了示例。但是不知何故,这仍然无法正常工作。不知道如何正确设置动画... :-/ 你有什么想法吗? - LeO
而且我的自定义转场动画的animationDuration也不适用吗? - LeO
2个回答

12

我也不太喜欢左右滑动的动画效果。你可以使用我准备的淡入淡出过渡动画。

你可以禁用 Angular Mat Tab 的动画效果,然后在 mat-tab-body-active 类中添加一些 CSS 关键帧动画。

要禁用动画效果,可以在 mat-tab 中添加以下代码。

<mat-tab-group [@.disabled]="true">

或者您可以在此链接中全局禁用它。

禁用动画后,请在您的style.css文件中添加以下内容。

.mat-tab-body.mat-tab-body-active {
  animation: fade 0.5s;
}


@keyframes fade {
  0% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}

请查看我的示例这里


5

根据您的代码,我猜测您尝试在淡出之前淡入一个新标签页。

使用Eldon's answer的方法,我建议进行一些小的更改:

.mat-tab-body {
    animation: fade-out 0.5s;
    opacity: 0;
}
.mat-tab-body.mat-tab-body-active {
    animation: fade-in 0.5s;
    opacity: 1;
}

@keyframes fade-in {
    0% {
        opacity: 0;
    }
    50% {
        opacity: 0;
    }
    100% {
        opacity: 1;
    }
}

@keyframes fade-out {
    0% {
        opacity: 1;
    }
    50% {
        opacity: 0;
    }
    100% {
        opacity: 0;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接