Search code examples
angularangular-forms

Retrieve date value from an Angular Reactive Form


I have created a Reactive Form in my Angular component with which I want to retrieve a date range from the user.

HTML

<form [formGroup]="dateRangeForm" (submit)="onSubmit(f)" #f>
            <div class="card-block">
                <div class="form-group">
                    <label for="start-date">Start Date: </label>
                    <input id="start-date"
                           type="date"
                           class="form-control"
                           formControlName="startDate"/>
                </div>
                <div class="form-group">
                    <label for="end-date">End Date: </label>
                    <input id="end-date"
                           type="date"
                           class="form-control"
                           formControlName="endDate">
                </div>
                <div class="card-footer separator">
                    <input type="submit" value="Search">
                </div>
            </div>
        </form>

TypeScript

 this.dateRangeForm = this.formBuilder.group({
      startDate: [ new Date(), Validators.required ],
      endDate: [ new Date(),Validators.required ],
    });

For my submit form, I am trying to retrieve the data from the form controls as follows.

onSubmit(form: FormGroup) {
    var startDate:string  = form.controls["startDate"].getRawValue();
    var endDate:string  = form.controls["endDate"].value;
  }

However, when I do so I get the following TypeError in my Dev Tools console, and I do not understand why if I have declared the form control in my FormGroup's group() method. I have tried changing the data type of the startDate and endDate to string, but I run into the same error.

ERROR TypeError: Cannot read properties of undefined (reading 'startDate')
    at LiveDashboardComponent.onSubmit (live-dashboard.component.ts:133:1)
    at LiveDashboardComponent_Template_form_submit_7_listener (template.html:7:43)
    at executeListenerWithErrorHandling (core.mjs:14931:1)
    at wrapListenerIn_markDirtyAndPreventDefault (core.mjs:14972:1)
    at HTMLFormElement.eval (platform-browser.mjs:459:1)
    at _ZoneDelegate.invokeTask (zone.js:443:1)
    at Object.onInvokeTask (core.mjs:26299:1)
    at _ZoneDelegate.invokeTask (zone.js:442:1)
    at Zone.runTask (zone.js:214:1)
    at ZoneTask.invokeTask [as invoke] (zone.js:525:1)

Solution

  • instead of passing the form object from the template to the ts file, you could use the FormGroup object from the ts file. standard practice is to use it like that. the param you passed on the onSubmit function probably isn't the type FormGroup.

    try accessing the FormGroup values as follows.

    onSubmit() {
      const startDate:string  = this.dateRangeForm.get("startDate").value;
      const endDate:string  = this.dateRangeForm.get("endDate").value;
    }