Home > Mobile >  FormControl's Not Resetting
FormControl's Not Resetting

Time:12-10

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.

CodePudding user response:

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">

CodePudding user response:

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

  • Related