简体   繁体   中英

Set color of matInput outline dynamically

I've got a basic Angular Material input field like this:

        <mat-form-field appearance="outline">
            <input matInput type="text">
            <button matSuffix mat-icon-button>
              <mat-icon>add</mat-icon>
            </button>
        </mat-form-field>

And want to change the color of the outline. For a fix color I found this example:

:host ::ng-deep {
    .mat-form-field-appearance-outline .mat-form-field-outline {
        color: red;
    }
}

Is there a way to use the value of a variable (in a ngFor loop) as the color of the underline?

You can use [style.--CSS-VARIABLE-NAME] in the html . Then consume it in the SCSS or CSS using var(--CSS-VARIABLE-NAME) .

For more info, please read this: https://angular.io/guide/class-binding#:~:text=To%20create%20a%20single%20style,following%3A%20%5Bstyle.width%5D%3D%22width%22 .

example.component.ts


@Component({
 // ...
})
export class Example {

  public myColor = ['red', 'blue', 'green'];

}

example.component.html


<ng-container *ngFor="let color of myColors">

  <mat-form-field appearance="outline" [style.--custom-color]="color">
    <mat-label>Input</mat-label>
    <input matInput />
  </mat-form-field>

</ng-container>

example.component.scss


:host ::ng-deep .mat-form-field-appearance-outline .mat-form-field-outline {
  color: var(--custom-color);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM