[Fixed] send age as birthdate when submitting reactive forms

Issue

When the user types age in input I want to send this age as birthdate, for a month and day today’s date.

"birthDate": "1996-04-20T20:43:40.909Z",

like this

.html

<input matInput formControlName="birthDate" type="text" class="form-control age" placeholder="Age" required>

.ts

  ngOnInit() {
    this.formGroup = this._formBuilder.group({
      formArray: this._formBuilder.array([
        this._formBuilder.group({
          birthDate: ['', [Validators.min(18), Validators.max(50)]],
        }),
      ])

    });
  }

 onSubmit() {
    console.log(this.formGroup.value);
    this.service.calculate(this.formGroup.value).subscribe(
      (res:any)=>{
        console.log(res);
      },
      err => {
        console.log(err);
      }
    );
  }
}

here is my stackblitz

Solution

const birthDateValue = 23; // Get value from the form control
const date = new Date();
const year = date.getFullYear() - birthDateValue;
date.setYear(year);

console.log(date.toISOString())

Leave a Reply

(*) Required, Your email will not be published