3

I am trying to reset a reactive form created by Angular Material (except the checkbox). I've tried to use this.formdata.reset(). It is resetting the form but it's making it touched. So I used this.formdata.markAsUntouched() but it's not making anything different. Here is my code below:

app.component.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, Validators, FormArray, FormControl, NgForm } from '@angular/forms';

export class FormComponent implements OnInit{

  public states = [];

  Gender: model[] = [{value: 'M', option: 'Male'}, {value: 'F', option: 'Female'}];
  Vehicles: model[] = [{value: '2 wheelers', option: '2 wheelers'}, {value: '4 wheelers', option: '4 wheelers'}];

  constructor(private _statesService: StatesService, private fb: FormBuilder) {}

  // Initialize each field of form with FormBuilder
  formdata = this.fb.group({
    name: ['', [Validators.required, Validators.minLength(3)]], phone: ['', [Validators.required, Validators.minLength(12)]],
    gender: ['', Validators.required], vehicles: new FormArray([],Validators.required)
  });

  // Retreiving values of form field
  get Name()
  {return this.formdata.get('name');}

  get Phone()
  {return this.formdata.get('phone');}

  get Vehiclesmethod()
  {return this.formdata.get('vehicles');}

  get Genderval()
  {return this.formdata.get('gender');}

  onCheckChange(event) {
    const formArray: FormArray = this.formdata.get('vehicles') as FormArray;

    /* Selected */
    if(event.target.checked){
      // Add a new control in the arrayForm
      formArray.push(new FormControl(event.target.value));
    }
    /* unselected */
    else{
      // find the unselected element
      let i: number = 0;

      formArray.controls.forEach((ctrl: FormControl) => {
        if(ctrl.value == event.target.value) {
          // Remove the unselected element from the arrayForm
          formArray.removeAt(i);
          return;
        }
        i++;
      });
    }
  }
  @ViewChild('f') private f: NgForm;
  // Submit method
  onSubmit()
  {
    if(this.formdata.invalid){return ;}
    console.log(this.formdata.value);
    alert('submitted');
    // Reset form
    this.formdata.reset();
    this.formdata.markAsUntouched();
  }
}

app.component.html

<form [formGroup]="formdata" (ngSubmit)="onSubmit()" #f="ngForm"> 
            <div class="form-row">
                <div class="col">
                    <p>
                        <mat-form-field appearance="outline" class="field_size">
                            <mat-label>Name</mat-label>
                            <input type="text" matInput formControlName="name">
                            <mat-error *ngIf="Name.errors?.required">Name required</mat-error>
                            <mat-error *ngIf="Name.errors?.minlength">Minimum 3 characters required</mat-error>
                        </mat-form-field>
                    </p>
                </div>
                <div class="col">
                    <p>
                        <mat-form-field appearance="outline" class="field_size">
                            <mat-label>Phone Number</mat-label>
                            <input type="tel" matInput appPhoneMask formControlName="phone" maxlength="12">
                            <mat-error *ngIf="Phone.errors?.required">Phone number required</mat-error>
                            <mat-error *ngIf="Phone.errors?.minlength">Number is less than 10 digits</mat-error>
                        </mat-form-field>
                    </p>
                </div>
            </div>

            <div class="form-row">
                <div class="col">
                    <label>Gender</label><br>
                    <mat-radio-group formControlName="gender">
                        <mat-radio-button *ngFor="let g of Gender; let i = index" [value]="g.value">{{ g.option }}</mat-radio-button>
                    </mat-radio-group><br>
                    <small *ngIf="Genderval.errors?.required" style="color: red;">Please select Gender</small>
                </div>
                <div class="col">
                    <label>Vehicles</label><br>
                    <div class="form-inline">
                        <span class="custome-control custom-checkbox mr-sm-2" *ngFor="let v of Vehicles,let i=index">
                            <input type="checkbox" class="custom-control-input" id="{{i}}" [value]="v.value" (change)="onCheckChange($event)">
                            <label for="{{i}}" class="custom-control-label">{{v.option}}</label>
                        </span>
                    </div>
                </div>
            </div>
            <div class="form-row">
                <button mat-flat-button color="primary" type="submit" class="button" [disabled]="!formdata.valid">Submit</button>
            </div>
        </form>

NOTE: The value is getting emptied for every fields in the FormBuilder part and also in the view part. But the checkbox in view part it's showing still checked.

Please help me out I've tried many ways but nothing is working fine.

8
  • You need to pass true/false values to the checkbox. You're passing v.value which is a string (aka a truthy value) which is why your checkbox is always checked. Dealing with checkboxes dynamically with formControl is tricky. You can check out my answer here if you want to dynamically produce boolean values and then map them to your string values. Commented Apr 3, 2020 at 4:25
  • tried now still it's getting remained checked !! Commented Apr 3, 2020 at 4:29
  • Why are you not using formControlName directive for checkbox, if you are using reactive form Commented Apr 3, 2020 at 4:32
  • @Chellappanவ yeah i know that but it was making both the checkboxes checked but the values weren't passed Commented Apr 3, 2020 at 4:43
  • You mean if you use reactive way? Commented Apr 3, 2020 at 6:01

3 Answers 3

3

You can get a reference to your ngForm like this:

<form [formGroup]="commentForm" **#commentNgForm="ngForm"** (submit)="replyTicket()"></form>

and then in your component get this refence with @ViewChild as this

 @ViewChild('commentNgForm') commentNgForm!: NgForm;

and finally you can use then in your method like this

this.commentNgForm.resetForm();
Sign up to request clarification or add additional context in comments.

Comments

0

I'm not sure if will work for entire form, but definitelly is ok for each FormControl. You need to specify in options place to not emit an event after changes.

this.formdata.reset('', {emitEvent: false});

after this, if your form is still marked as touched, try your solution + check form changes:

constructor(private cd: ChangeDetectorRef) {}

this.formdata.markAsUntouched();
this.cd.detectChanges();

Comments

-1

You should use the resetForm() method. So instead of writing this.formdata.reset() write this.formdata.resetForm(), and no need to use the markAsUntouched

Source: https://itnext.io/to-reset-a-form-or-to-resetform-555d3da47c52

1 Comment

it gives an error. like there is no resetForm() method

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.