You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为MatTabNav添加水平滚动自定义动画并替换默认动画

MatTabNav自定义滚动渐隐动画实现方案

你的核心疑问解答:需要为新动画定义对应触发器,Angular Material默认将MatTabNav的滚动动画封装为内部逻辑,无法直接修改,需要先禁用默认动画,再绑定自定义动画触发器实现渐隐效果,具体实现步骤如下:


步骤1:禁用默认滚动动画

先通过全局CSS覆盖掉MatTabNav内置的平移动画,避免和自定义动画冲突,在全局styles.scss中添加如下代码:

/* 禁用MatTabNav默认平移动画 */
.mat-tab-nav-bar .mat-tab-label-container {
  transition: transform 0s !important;
}
.mat-tab-nav-bar .mat-tab-header-pagination {
  transition: all 0s !important;
}

步骤2:导入动画依赖并定义自定义触发器

修改component.ts文件,首先导入Angular动画相关依赖,然后在组件配置中添加渐隐动画触发器,并重写默认滚动逻辑:

import {Component, ViewChild, AfterViewInit} from '@angular/core';
import {ThemePalette} from '@angular/material/core';
import {MatTabNav} from '@angular/material/tabs';
// 导入动画依赖
import { trigger, style, animate, transition } from '@angular/animations';

@Component({
  selector: 'tab-nav-bar-basic-example',
  templateUrl: 'tab-nav-bar-basic-example.html',
  // 定义渐隐动画触发器
  animations: [
    trigger('fadeScroll', [
      transition('* => *', [
        // 滚动切换时先将容器透明度设为0
        style({ opacity: 0 }),
        // 300ms过渡到完全显示,可自行调整时长和缓动函数
        animate('300ms ease-in', style({ opacity: 1 }))
      ])
    ])
  ]
})
export class TabNavBarBasicExample implements AfterViewInit {
  links = ['First', 'Second', 'Third'];
  activeLink = this.links[0];
  background: ThemePalette = undefined;
  @ViewChild(MatTabNav) matTabNav: MatTabNav;

  ngAfterViewInit() {
    // 重写默认滚动方法,取消默认平移动画
    const originalScrollFn = this.matTabNav.scrollToIndex;
    this.matTabNav.scrollToIndex = (index: number, animationDuration?: number) => {
      // 调用原始滚动方法时强制动画时长为0,禁用平移效果
      originalScrollFn.call(this.matTabNav, index, 0);
    };
  }

  toggleBackground() {
    this.background = this.background ? undefined : 'primary';
  }

  addLink() {
    this.links.push(`Link ${this.links.length + 1}`);
  }
}

步骤3:模板绑定动画触发器

修改component.html,将定义好的fadeScroll触发器绑定到tab导航容器上,触发器的输入值绑定当前激活的链接,每次激活链接变化时就会触发渐隐动画:

<nav 
  mat-tab-nav-bar 
  [backgroundColor]="background"
  [@fadeScroll]="activeLink"
>
  <a mat-tab-link *ngFor="let link of links"
     (click)="activeLink = link"
     [active]="activeLink == link"> {{link}} </a>
  <a mat-tab-link disabled>Disabled Link</a>
</nav>

<button mat-raised-button class="example-action-button" (click)="toggleBackground()">
  Toggle background
</button>
<button mat-raised-button class="example-action-button" (click)="addLink()">
  Add link
</button>

如果需要更精细的渐隐控制(比如仅滚动超出视野的tab做渐隐、而非整个容器),可以单独给每个mat-tab-link绑定动画触发器,配合ElementRef判断元素可见性来触发即可。

内容的提问来源于stack exchange,提问作者MrScf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 14:36:03