How do reset a specific field in form?

Viewed 58

How to reset not the whole form, but only one field? And so that when the field is reset, it gets the value '', not null

 clear(): void {
    this.form.value.search = '';
    // this.form.reset();
    this.applyFilter();
  }
4 Answers

Extract the control from the form, and call reset on it with ''.

clear(): void {
    this.form.get('value')?.reset('');
    this.applyFitler();

  }

Assuming you are using HTML, what you have to do is passing an HTMLInputElemenet, like this:

clear(field: HTMLInputElement): void {
    field.value = '';
  }

And you will have to name your field like this:

<input
   type="text"
   placeholder="Total"
   #field
/>

Look the name with the #, it must be the same as you are passing in your function.

clear(formControlName): void {
  this.form.patchValue({
    formControlName : ''
   })
  }

You can create a common function like this and pass the form-control name as a parameter of the function

you can reset the form field using

this.form.get("value").reset("");

you can check the reset documentation

or you can create a general function that when you call it and pass the field name as a parameter to it, will reset the field to empty string

resetFieldToEmptyString(FieldName:string) {
  this.form.get(FiledName).reset("")
}
Related