I have some simple angular 2 component with template. How to clear form and all fields after submit?. I can't reload page.
After set data with date.setValue('')
field is stil touched
.
import {Component} from 'angular2/core';
import {FORM_DIRECTIVES, FormBuilder, ControlGroup, Validators, Control} from 'angular2/common';
@Component({
selector: 'loading-form',
templateUrl: 'app/loadings/loading-form.component.html',
directives: [FORM_DIRECTIVES]
})
export class LoadingFormComponent {
private form:ControlGroup;
private date:Control;
private capacity:Control;
constructor(private _loadingsService:LoadingsService, fb:FormBuilder) {
this.date = new Control('', Validators.required);
this.capacity = new Control('', Validators.required);
this.form = fb.group({
'date': this.date,
'capacity': this.capacity
});
}
onSubmit(value:any):void {
//send some data to backend
}
}
loading-form.component.html
<div class="card card-block">
<h3 class="card-title">Loading form</h3>
<form (ngSubmit)="onSubmit(form.value)" [ngFormModel]="form">
<fieldset class="form-group" [class.has-danger]="!date.valid && date.touched">
<label class="form-control-label" for="dateInput">Date</label>
<input type="text" class="form-control form-control-danger form-control-success" id="dateInput"
min="0" placeholder="Enter loading date"
[ngFormControl]="form.controls['date']">
</fieldset>
<fieldset class="form-group" [class.has-danger]="!capacity.valid && capacity.touched">
<label class="form-control-label" for="capacityInput">Capacity</label>
<input type="number" class="form-control form-control-danger form-control-success" id="capacityInput"
placeholder="Enter capacity"
[ngFormControl]="form.controls['capacity']">
</fieldset>
<button type="submit" class="btn btn-primary" [disabled]="!form.valid">Submit
</button>
</form>
</div>
Here is how I do it in Angular 7.3
There was no need to call
form.clearValidators()
Below code works for me in Angular 4
Here's how I do it Angular 8:
Get a local reference of your form:
And whenever you need to reset the form, call
resetForm
method:You will need
FormsModule
from@angular/forms
for it to work. Be sure to add it to your module imports.There is a new discussion about this (https://github.com/angular/angular/issues/4933). So far there is only some hacks that allows to clear the form, like recreating the whole form after submitting: https://embed.plnkr.co/kMPjjJ1TWuYGVNlnQXrU/
To angular version 4, you can use this:
But, you could need a initial value like:
It is important to resolve null problem in your object reference.
reference link, Search for "reset the form flags".