Reputation: 1524
I have created a function in one of my component file that resets the form(myform):
onSubmit() {
if (this.myform.valid) {
console.log("Form Submitted!");
this.myform.reset();
}
}
It works perfectly fine resetting the whole form. Is it possible to reset some of the form elements, while keeping others unchanged?
Upvotes: 24
Views: 45289
Reputation: 76
UPDATE:
I just had this issue and although the accepted answer works, it has some tslint warnings. I ended up doing:
this.myForm.get('formControlName').setValue(null);
I'm working with Angular 8.
And if you want to do it for several fields this works too:
private controlNames = ['nameOne', 'nameTwo'];
this.controlNames.forEach((value: string) => this.myForm.get(value).setValue(null));
Upvotes: 4
Reputation: 1535
Dynamically deletion of FormControl value:
private _clearFormGroupControlValue(formControlName: string) {
this.formGroup.get(formControlName).setValue(null);
}
or
private _clearFormGroupControlValue(formControlName: string) {
this.formGroup.controls[formControlName].reset();
}
or
private _clearFormGroupControlValue(formControlName: string) {
this.formGroup.controls[formControlName].patchValue(null || '');
}
Upvotes: 1
Reputation: 1259
In your html
<select formControlName="idSala" (change)="clearField(1)">
<option value="">Selecione uma sala</option>
</select>
<input type="text" formControlName="titulo">
<input formControlName="dataHoraInicial" type="datetime-local">
TS
clearField(value) {
if (value == 1) {
this.formularioDeAgendamentoSala.controls['titulo'].reset();
this.formularioDeAgendamentoSala.controls['dataHoraInicial'].reset();
}
}
Upvotes: 2
Reputation: 305
Yes you can access the controls using this.myform.controls
get the control and call reset()
on it
Upvotes: 3
Reputation: 191
try this one:
clearForm() {
this.myForm.get('comments').reset();
this.myForm.get('name').reset();
}
and call this function where you submit form.
Upvotes: 19