htmlcssangularsassangular-material

How could I apply different colors for mat-form-field "formControl" depends on the state of it?


I have this HTML code:

<mat-form-field class="me-3" appearance="outline" class="filterText">
        <mat-label [ngClass]="{'mat-label-error': form.get('result')?.invalid && form.get('result')?.touched}">
                    {{ 'evaluation_detail.result' | translate }}
        </mat-label>
        <mat-select id="result" formControlName="result" data-testid="result-select">
                <mat-option *ngFor="let res of resultOptions" [value]="res.id">{{res.name | translate }}</mat-option>
        </mat-select>
</mat-form-field>

Then, I have this css code:

::ng-deep .mat-primary:not(.ng-invalid) .mat-mdc-select-arrow {
    color: red !important;
}
::ng-deep .mat-mdc-select-arrow {
    color: var(--primary-color) !important;
}

I have been using this code trying to change colors of the mat-form-field depends on the state of it, but it is not working for me.


Version:

@angular-devkit/architect 0.1703.0 
@angular-devkit/build-angular 17.3.0 
@angular-devkit/core 17.3.0 
@angular-devkit/schematics 17.3.0 
@schematics/angular 17.3.0 
rxjs 7.8.1 
typescript 5.3.3 
zone.js 0.14.4

Solution

  • Angular Material 17:

    Basically you can do an inspect element and customize the color based on the CSS variables used. We do not need ::ng-deep when we work with CSS variables.

      mat-select {
        --mat-select-enabled-arrow-color: yellow;
        --mat-select-focused-arrow-color: yellow;
      }
    
      mat-select.ng-invalid:not(.ng-touched):not(.ng-pristine) {
        --mat-select-enabled-arrow-color: red;
        --mat-select-focused-arrow-color: red;
      }
    

    Stackblitz Demo


    Angular 19:

    Check the angular styling section for mat-form-field and apply the necessary customizations.

    form-field - Styling Docs

    @use '@angular/material' as mat;
    
    // Customize the entire app. Change :root to your selector if you want to scope the styles.
    :host {
      @include mat.form-field-overrides((
        filled-caret-color: orange,
        filled-focus-active-indicator-color: red,
      ));
    }