Search code examples
angularangular-materialplaceholder

How to customize the placeholder in angular 7


I am trying to use the placeholder for one of my form field.

<mat-form-field>
    <mat-label>date</mat-label>
      <input class="date-picker form-control" ngx-mydatepicker
             placeholder="yyyy-mm-dd"/>

enter image description here

i get this output. But I donot want the mat-label. However when I remove the label it displays like this enter image description here

How do I make this look like the placeholder above.


Solution

  • As stated here,

    If you want to create a legacy form field with a placeholder but no label, you will need to specify an empty label to prevent the placeholder from being promoted.

    So, you can try following:

    <mat-form-field class="example-full-width">
      <mat-label></mat-label>
      <input matInput placeholder="Just a placeholder">
    </mat-form-field>
    

    I created a stackblitz, please check the most bottom input field.

    UPDATE

    In order to have placeholder in both focused and blured states, you can try to add *ngIf statement to <mat-label>, which value will be changed by focus and blur events:

    <mat-form-field class="example-full-width">
      <mat-label *ngIf="focused"></mat-label>
      <input matInput 
             placeholder="Just a placeholder" 
             (blur)="focused=false" 
             (focus)="focused=true">
    </mat-form-field>