Display Mat-hint only on corresponding input focus

Viewed 3551

I have a mat-hint element added in my html. I want to display mat-hint only when users focus is on corresponding form-field & hide the hint on focusout. How to achieve this scenario for all form-fields.

<mat-hint align="end">Max 50 characters</mat-hint>
2 Answers

You can use (focus) and (focusout) with reference called focusState

<input name="date" type="text" (focus)="focusState = true" (focusout)="focusState = false">
<mat-hint align="end" *ngIf="focusState">Max 50 characters</mat-hint>

Edit

To handle the multiple items

<div *ngFor="let item of array">
   <input #item name="date" type="text" (focus)="item.alt = true" (focusout)="item.alt = false">
   <mat-hint align="end" *ngIf="item.alt">Max 50 characters</mat-hint>
</div>

I solved this by css only. Hide when not focused.

.mat-form-field:not(.mat-focused) .mat-hint {
    display: none;
}
Related