How to stop a floating-label from floating?

46 views Asked by At

I need this label stop from floating. I need it to be still. The input is from Angular Material. https://material.angular.io/components/form-field/examples

enter image description here

The code is the following one:

Phone

If someone can help me, I'am a rookie in programming. Thanks in advance.

I tried putting classes in CSS but none of them worked.

.mat-form-field-appearance-outline .mat-form-field-label {
    transform: translateY(-50%);
}

.mat-mdc-floating-label.mat-mdc-form-field {
    transform: none !important;
}

.mat-mdc-form-field .mat-mdc-floating-label.mat-mdc-form-field {
    transform: none !important;
}

.mat-mdc-form-field.ng-touched .mat-mdc-floating-label.mat-mdc-form-field {
    transform: none !important;
}
.mat-mdc-form-field.ng-touched .mat-mdc-floating-label.mat-mdc-form-field[ng-reflect-floating="true"] {
    transform: none !important;
}

.mat-form-field.mat-focused .mat-form-field-label {
    transform: none !important;
}

1

There are 1 answers

0
Alpine A110R On

You can use the floatLabel propertie like this:

  <mat-form-field [floatLabel]="'always'">
    <mat-label>Placeholder</mat-label>
    <input matInput placeholder="Simple placeholder">
  </mat-form-field>

The default value is auto in a form-field, so use always to stop floating behaviour.

And to avoid duplicate floatLabel properties in your template, angular material provides MAT_FORM_FIELD_DEFAULT_OPTIONS providers that you can inject in your component like:

  providers: [
    {
      provide: MAT_FORM_FIELD_DEFAULT_OPTIONS,
      useValue: {
        floatLabel: 'always'
      },
    }
  ],

Template:

      <mat-form-field>
        <mat-label>Placeholder</mat-label>
        <input matInput placeholder="Simple placeholder">
      </mat-form-field>