Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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' }
   }
  ]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading