How to clear an Angular reactive form input values
Asked Answered
K

3

5

I have a simple reactive form set up like this

constructor(private scheduleService: ScheduleService, fb: FormBuilder) {
this.searchForm = fb.group({
  from: ["", Validators.required],
  to: ["", Validators.required],
  date: ["", Validators.required]
});
}

I want to clear the form fields by click on a button that calls the clear function. My clear function currently doesn't work and looks like this

clear() {
console.log("Reset all search form fields to null.");

this.searchForm.from = "";
this.searchForm.to = "";
this.searchForm.date = "";
}

What is the right way to clear form input fields when working with angular reactive forms? How can I achieve this by using a single statement to reset all form fields instead of individual fields?

Ketone answered 1/3, 2019 at 2:53 Comment(2)
Possible duplicate of Cleanest way to reset formsJaella
@ConnorsFan thanks for your comment. Found the solution there.Ketone
S
12
  ngOnInit(): void {
    this.searchForm = this.fb.group({
      from: ['', Validators.required],
      to: ['', Validators.required],
      date: ['', Validators.required]
    });
  }

reset complete form

  resetForm() {
    this.searchForm.reset();
  }

reset individual field

  resetFrom() {
    this.searchForm.get('from').reset();
  }
Sharpedged answered 17/5, 2021 at 10:19 Comment(0)
L
0

"data" will be your form data

   searchForm!: FormGroup;

   this.searchForm = this.formBuilder.group({
      name: [''],
      address: ['']
    });

     clearForm() {
        try{
          let data={
               name:'',
               address:''
              }
           this.searchForm.reset(data);
         }
        catch(ex){
          console.log(ex)
         }
    
        }
Lorindalorine answered 28/11, 2023 at 8:19 Comment(0)
L
-1

for reset one input

 ngOnInit(): void {
    this.searchForm = this.fb.group({
      from: ['', Validators.required],
      to: ['', Validators.required],
      date: ['', Validators.required]
    });
  }

convenience getter for easy access to form fields

  get f() { return this.registerForm.controls; }

reset one field exmple (from )

this.f.from.reset();

Lindgren answered 16/4, 2022 at 13:8 Comment(1)
This is absolutely wrong, first, it doesn't solve the issue, then even if it does, this is going to reset the whole form, whereas you said it'll reset one field!Fitzger

© 2022 - 2024 — McMap. All rights reserved.