'How to clear an Angular reactive form input values

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?



Solution 1:[1]

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

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sanka sanjeewa
Solution 2 Akrimi Zoulfa