21

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, but is it possible to just reset some of the elements and keeping other the same way.

Hitesh Kansagara
  • 3,308
  • 3
  • 17
  • 32
Atul Stha
  • 1,404
  • 8
  • 23
  • 46

6 Answers6

49

try this:

this.myform.controls['comments'].reset()
B.Nbl
  • 556
  • 1
  • 5
  • 7
  • How can you add multiple fields to this? say `this.myform.controls['comments', 'name'].reset()` I can't find this way of doing it in the documentation. – Keithers Jan 17 '19 at 22:04
  • @Keithers try this : this.myform.reset({ comments: null, name: null}) – Abdes Feb 10 '19 at 21:56
  • @Abdessamad tried it but did not work, I had to replicate the code twice for the different control names `this.myform.controls['comments'].reset(), this.myform.controls['name'].reset()` – Onen simon Apr 30 '19 at 14:21
  • It took me way to long to find this, thanks I think this is the cleanest solution. – Dave Collier Mar 11 '20 at 17:01
17

try this one:

  clearForm() {
    this.myForm.get('comments').reset();
    this.myForm.get('name').reset();
  }

and call this function where you submit form.

Cucer Denis
  • 171
  • 1
  • 4
3

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.map((value: string) => this.myForm.get(value).setValue(null));
2

Yes you can access the controls using this.myform.controls get the control and call reset() on it

  • one of my controls name is `comments` so i wrote `this.myform.controls.comments.reset()`. But i get error 'Unresolved variable comments' – Atul Stha May 06 '18 at 07:58
2

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();
}

}

Consule
  • 1,059
  • 12
  • 12
1

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 || '');
}

khizer
  • 1,242
  • 15
  • 13