In my form, I collect various values, one of which is the birthdate in date-time format. I want to convert this into an age. The conversion function seems to be working fine when I test it with a dummy date like "10/10/1980"
. However, when I try to calculate the age using the actual value from the form which is this.f.birthdate.value
, it returns
undefined
Interestingly, this.f.birthdate.value
does display the date time when I log the entire form, so I'm puzzled why it shows undefined during the calculation.
page.html
<form>
...
<ion-item class="input-item">
<ion-label>Date of Birth</ion-label>
<ion-datetime display-format="DD/MM/YYYY" picker-format="DD MMMM YYYY" formControlName="birthdate" required></ion-datetime>
</ion-item>
<ion-button
type="submit"
(click)="calculateAge()"
[disabled]="!signupForm.valid"
> Sign Up </ion-button>
</form>
page.ts
public birthday: string;
public age: number;
...
ngOnInit() {
this.signupForm = new FormGroup({
'birthdate': new FormControl(Validators.required)
});
}
// convenience getter for easy access to form fields
get f() {
console.log(this)
return this.signupForm.value;
} // value or controls
public calculateAge(): void { // birthday is a date
this.birthday = this.f.birthdate.value;
if (this.birthday) {
var timeDiff = Math.abs(Date.now() - new Date(this.birthday).getTime());
this.age = Math.floor(timeDiff / (1000 * 3600 * 24) / 365.25);
console.log(this.age);
}
}
submit() {
this.authService.apiSignup(this.f.username.value,
this.f.email.value, this.f.password.value, this.age, this.f.gender.value)
...
}