The function is not retrieving the value from the form

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

Answer №1

Ensure you include the formGroup directive within your form tags and link it to your reactive form:

<form [formGroup]="signupForm">
...
 <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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What steps should I take to resolve the issue of "Unable to read property of undefined"?

Can anyone help me resolve this error? I've attempted to fix it without success. TypeError: Cannot read property 'user' of undefined App C:/Users/Bogosyna/Desktop/IT job projects/roro-facebook/src/App.js:11 8 | import {useStateValue} from ...

What is the best way to sort through data if I enter more than three characters to filter the results?

Hey there, I'm currently in the process of developing a search bar that functions by displaying only filtered last names from a table when more than 3 characters are typed. The condition for filtering is empty. Here is the HTML code: <mat-form-fi ...

Steps for developing an Ionic blank application

Hello, I am new to Cordova Ionic and I am looking to create a blank app. I have created it, but I am unsure where I should write the controllers. run(function($ionicPlatform) { $ionicPlatform.ready(function() { // Hide the accessory bar by default ( ...

Error encountered during predeploy parsing in Firebase Functions when running lint operation

Whenever I attempt to deploy my Firebase Functions, I encounter a parse error. My development environment is cmd on Windows and I am coding in JavaScript. It's strange because a few days ago, I successfully deployed my Functions using Mac, but today w ...

Ensure that Angular FormGroup POST is correctly de-marshaled in conjunction with associated objects

Summary In a complex Angular 2.x + Spring Data REST + Spring Boot 1.4 project, the challenge lies in defining JSON object references that can be successfully de-marshaled by Spring into the domain model. Key Points Consider a scenario where a recipe boo ...

What is the top choice instead of using the jQuery toggle() method?

After jQuery deprecated the toggle() method, I began searching for alternative ways to toggle classes on Stack Overflow. I came across various other methods to accomplish the same task (Alternative to jQuery's .toggle() method that supports eventData? ...

The error message "Unable to access the property 'map' of an undefined component" is displayed when trying to call

Introducing my newest component, userRow: Let's take a closer look at userRow: export default function UserRow(props, {data}) { const style = styles(); const userList = data.map((row) => { return { name: row, details: row }; ...

Clear Vuex state upon page refresh

In my mutation, I am updating the state as follows: try { const response = await axios.put('http://localhost:3000/api/mobile/v3/expense/vouchers/form_refresh', sendForm, { headers: { Accept: 'application/json', 'C ...

"Encountered an error message: Unable to retrieve property 'getCapabilities' due to a TypeError

Everything was going smoothly with my tests until I encountered an issue when the browser.getCapabilities(); method was called in the OnComplete function, resulting in an error. //The HTMLReport is triggered once all tests are completed onComplete: f ...

Ways to conceal just a portion of the bootstrap sidebar?

I'm looking to create a sidebar using 'vue-bootstrap' that can be hidden when clicked, but I only want to hide 80% of the width of the sidebar. How can I achieve this effect of partially hiding the sidebar? <b-button v-b-toggle.sidebar-1 ...

Is it possible to transform the original object while converting between different types in Typescript?

Consider having two distinct interfaces: interface InterfaceOne { myString: string, myNum: number } interface interfaceTwo extends InterfaceOne { myBool: boolean } Utilizing the TypeScript code below: let somedata: interfaceTwo = { my ...

How can HTML text be highlighted even when it's behind a transparent div?

In my React application, I am facing an issue with a transparent div that serves as a dropzone for draggable elements. This div covers text and also contains children elements that may have their own text content. <Dropzone> <SomeChild> . ...

How to automatically close an Angular 2 material dialog

Using angular2 material's MdDialog, I have implemented a form display feature. Upon form submission, a request is made to the backend. If the request is successful, I need to automatically close the dialog. However, if the backend request fails, the ...

Oops! Unable to locate the module specifier "highlight.js" in the ES6 module compiled from TypeScript

I'm currently experimenting with the highlight.js library for code highlighting, and while it does support ES modules, I encountered an issue when trying to use it in an ES6 module compiled from TypeScript. The error message that pops up is: Uncaught ...

Establish a connection to an already existing database using Mongoose

I've been exploring the inner workings of MongoDB lately. After setting up a local database, I created a collection with the following document: db.user.find().pretty() { "_id" : ObjectId("5a05844833a9b3552ce5cfec"), " ...

Ensure a button is automatically highlighted within an active class script

I have created a set of buttons that allow users to change the font family of the text. I would like the border and text color to update automatically when a specific option is selected. Currently, the JavaScript code works well, but when the page first l ...

Issues with Bootstrap 4 accordions failing to expand on mobile devices

I'm facing a strange issue with my Bootstrap 4 accordions. They work fine in responsive mode on Chrome, but when I try it on an Android phone or iPhone, they refuse to open. I'm really puzzled by this. Any thoughts on what might be causing this? ...

Searching in MongoDB using periods

Hey, I'm running into an issue with the full text search feature in MongoDB. Let me give you an example: db.test.insert({fname:"blah.dll"}) db.test.insert({fname:"something.dll"}) db.test.ensureIndex({fname:"text"}) After setting this up, if I run.. ...

Tips for preventing the text from changing within a textbox using the identical ng-model

I have similar forms with the following structure: <form ng-submit="addReply(x)" class="dd animated slideInDown" > <div class="form-group"> <text-angular ng-model="form.reply"></text-angular> ...

Looking for the function to activate when the enter key is pressed

I have a search box which is a text type and has a click button that initiates the Find() function. How can I enable searching by pressing Enter inside the textbox? ...