David
David

Reputation: 6111

FormControl's Not Resetting

I am trying to create a clear input functionality, but running into an issue. When I start my server, the inputs are automatically filled in because I have my credentials saved in the browser. When I click on the clear icon button, the button disappears, but the control still shows the value. However, if output the control's value, it says that it is null.

This is my template:

<mat-form-field>
    <mat-label>Email</mat-label>
    <input matInput type="email" fieldControlName="email">
    <button *ngIf="form?.get('email')?.value" matSuffix mat-icon-button aria-label="Clear" (click)="resetValue('email')">
        <mat-icon>close</mat-icon>
    </button>
</mat-form-field>

and this is the resetValue method:

resetValue(fieldControlName: string): void {
    this.form?.get(fieldControlName)?.reset(null);
}

Stackblitz Demo: https://stackblitz.com/edit/angular-ivy-qmb3q1

I've tried calling updateValueAndValidity immediately after calling reset, but that doesn't work either. The value still shows up in the DOM but the value is null in the console.

Upvotes: 0

Views: 992

Answers (2)

SaschaLeh
SaschaLeh

Reputation: 198

You are using the reactive-forms approach right?

Then try it with "formControlName", because there is no corresponding attribute like "fieldControlName". Maybe due to that the referencing to your form object is not working.

 <input
      #myEmail
      matInput 
      type="email" 
      formControlName="email">

Upvotes: 1

Andres2142
Andres2142

Reputation: 2897

Not sure why visually speaking the values remain the same but, you could do this by removing those prefilled values like this:

<mat-form-field>
    <mat-label>Email</mat-label>
    <input
      #myEmail
      matInput 
      type="email" 
      fieldControlName="email">
    <button 
      *ngIf="form?.get('email')?.value" 
      matSuffix 
      mat-icon-button 
      aria-label="Clear" (click)="resetValue('email'); myEmail.value = ''">
        <mat-icon>close</mat-icon>
    </button>
</mat-form-field>

By adding a local reference to your HTML element and, besides executing resetValue, you also "reset" that value visually

Upvotes: 1

Related Questions