根据条件更改背景颜色步进器 angular material

Change background color stepper angular material with condition

我会在 Angular Material 项目中动态更改步进器的颜色。每个步骤我可以有多个状态。例如:

state: OK (should be green)
state: REFUSED (should be red)

所以,这就是我到目前为止所做的

<mat-horizontal-stepper>
                     <mat-step state="schedule">
                        <ng-template matStepLabel>
                            <span [ngClass]="{'ok-step': status == 'OK', 'step-refused': status == 'REFUSED'}" *ngIf="(status == 'OK' || status == 'REFUSED'); else default">
                                {{status}}
                            </span>
                            <ng-template #default>
                                Default state
                            </ng-template>
                        </ng-template>
                    </mat-step>
 </mat-horizontal-stepper>

这里我可以动态改变文字的颜色。有用。但我无法更改步进器背景的颜色。我可以这样做:

::ng-deep.mat-step-header .mat-step-icon-selected, .mat-step-header .mat-step-icon-state-done, .mat-step-header .mat-step-icon-state-edit {
    background-color: #dd2c00 !important
}

但是还有一个问题。这样我就不能设置2种不同的颜色。只有一个。我不能根据状态设置红色或绿色。有没有可能做到这一点?

我想在这里而不是使用直接的十六进制颜色。您可以使用变量并根据可以设置背景颜色的条件在.ts文件中设置变量的值。

所以根据我的解决方案,您应该将 .scss 文件更新为以下代码

 ::ng-deep.mat-step-header .mat-step-icon-selected, .mat-step-header .mat-step-icon- 
   state-done, .mat-step-header .mat-step-icon-state-edit {
   background-color: var(--background)!important
   }

并且您应该在 .ts 文件中添加以下行

if(status === 'Ok')
 {
  document.body.style.setProperty('--background', 'red')
 }
 else if(status === 'REFUSED')
 {
 document.body.style.setProperty('--background', 'red')
 }