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

如何在Angular应用中修改动画mat-progress-bar进度条不同进度下的颜色

可以通过动态绑定CSS类的方式实现需求,具体实现如下:

1. 修改组件TS逻辑

首先优化定时器逻辑,避免进度超过100后继续累加,同时新增对应进度的类名判断逻辑:

// 组件类内代码
progress: number = 0;
private timer: number | null = null;

ngOnInit() { 
  this.timer = window.setInterval(() => { 
    // 进度到100后停止累加,清除定时器
    if (this.progress < 100) {
      this.progress += 1; 
    } else {
      this.clearTimer();
    }
  }, 100)
}

// 组件销毁时清除定时器,避免内存泄漏
ngOnDestroy() {
  this.clearTimer();
}

private clearTimer() {
  if (this.timer) {
    clearInterval(this.timer);
    this.timer = null;
  }
}

// 根据进度值返回对应的样式类
get progressBarClass(): string {
  if (this.progress >= 90) return 'progress-red';
  if (this.progress >= 70) return 'progress-yellow';
  // 70%以下返回默认样式类,可按需修改
  return 'progress-default';
}

2. 添加样式代码

可以选择把样式写到全局的styles.css里,或者组件对应的样式文件中:

全局styles.css写法:

/* 70%以下默认蓝色 */
.progress-default .mat-progress-bar-fill::after {
  background-color: #2196f3 !important;
}
/* 70%-90%黄色 */
.progress-yellow .mat-progress-bar-fill::after {
  background-color: #ffc107 !important;
}
/* 90%以上红色 */
.progress-red .mat-progress-bar-fill::after {
  background-color: #f44336 !important;
}

组件样式文件写法:

需要加::ng-deep穿透Angular样式隔离,不推荐长期使用,优先全局样式方案:

::ng-deep .progress-default .mat-progress-bar-fill::after {
  background-color: #2196f3 !important;
}
::ng-deep .progress-yellow .mat-progress-bar-fill::after {
  background-color: #ffc107 !important;
}
::ng-deep .progress-red .mat-progress-bar-fill::after {
  background-color: #f44336 !important;
}

3. 更新HTML模板

给mat-progress-bar绑定动态类即可:

<mat-progress-bar 
  style="height: 10px" 
  mode="determinate" 
  [value]="progress"
  [ngClass]="progressBarClass"
>
</mat-progress-bar>

如果你使用了Angular Material自定义主题,也可以直接绑定[color]属性到预设的主题色,无需额外写样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 13:06:04