-->

How to hide placeholder onclick in material

2020-08-10 06:22发布

问题:

I am using simple form-field input component as in below code

<mat-form-field class="example-form-field" >
     <input matInput type="search" placeholder="Search"  >
</mat-form-field>

On entering the input fieled by default the placeholder will go above.

How can i hide the placeholder on entering to the input field?

回答1:

You can try:

DEMO ----> Solution

You can also create Directive for same

You can replace (click) ----> (focus) as you need

 <mat-form-field floatLabel=never>
     <input (click)="checkPlaceHolder()" (blur)="checkPlaceHolder()" matInput placeholder=" {{myplaceHolder}} ">
 </mat-form-field>

In TS:

myplaceHolder: string ='Enter Name'

 checkPlaceHolder() {
    if (this.myplaceHolder) {
      this.myplaceHolder = null
      return;
    } else {
      this.myplaceHolder = 'Enter Name'
      return
    }
  }


回答2:

I came into this question when looking for a way of hiding the placeholder when the input field is not empty, the solution I found is a modification of Krishna's, replacing the mat-form-field floatLabel argument from always to never:

<div class="example-container">
  <mat-form-field
      [floatLabel]="'never'">
    <input matInput placeholder="Simple placeholder" required>
  </mat-form-field>
</div>


回答3:

you can try this solution.

use [floatLabel]="'always'"

I have create a demo on Stackblitz

<div class="example-container">
  <mat-form-field
      [floatLabel]="'always'">
    <input matInput placeholder="Simple placeholder" required>
  </mat-form-field>
</div>


回答4:

This is a only-CSS solution that worked for me.

The first CSS directive is for when the input is focused.

The second is for when the input has a valid value and is not focused.

.mat-form-field.mat-focused .mat-form-field-label, input.ng-valid+span.mat-form-field-label-wrapper .mat-form-field-label{
    display: none !important;
}