6

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?

2
  • 1
    Possible duplicate of Cleanest way to reset forms Commented Mar 1, 2019 at 2:56
  • 2
    @ConnorsFan thanks for your comment. Found the solution there. Commented Mar 1, 2019 at 3:02

3 Answers 3

13
  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();
  }
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

1 Comment

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.