Reputation: 1068
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.
Upvotes: 3
Views: 8941
Reputation: 174
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();
Upvotes: 3
Reputation: 143
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
Upvotes: -1
Reputation: 2598
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();
Upvotes: 0