Search code examples
cssangularangular-materialmat-selectmat-form-field

How can I keep text of a mat-select fixed on component's border?


could someone tell how I do a mat-select field text stay fixed on component's border, like this (and put the placeholder too, if possible), even without click on it:

enter image description here

The default is the text be in middle of component and on click event, the text up to his border:

enter image description here

My component implementation:

<mat-form-field appearance="outline">
  <mat-label>Age</mat-label>
  <mat-select matNativeControl required>
     <mat-option *ngFor="let age of ages" [value]="age">{{age}}</mat-option>
  </mat-select>
</mat-form-field>

I tried to inspect on Developer tools about the css responsible to format the component on clicked, but without success.


Solution

  • You need to use the floatLabel input.

    Check docs

    <mat-form-field appearance="outline" floatLabel="always">
      <mat-label>Age</mat-label>
      <mat-select matNativeControl required>
         <mat-option *ngFor="let age of ages" [value]="age">{{age}}</mat-option>
      </mat-select>
    </mat-form-field>
    

    If you want this behaviour in all form fields you can use the MAT_FORM_FIELD_DEFAULT_OPTIONS to provide default config.

    import {MAT_FORM_FIELD_DEFAULT_OPTIONS} from '@angular/material/form-field';
    ...
    
     providers: [
       {
         provide: MAT_FORM_FIELD_DEFAULT_OPTIONS,
         useValue: { floatLabel: 'always' }
       }
      ]