What is the best way to extract age data from an Angular form group function and save it to the back-end?

I stumbled upon an interesting function in another post that checks whether a person is 18 years old or older. I would like to convert and store the age in the backend separately, but the challenge is that I don't have an age input in the HTML. Here's the code snippet:

    this.SignupForm = new FormGroup({
            'username': new FormControl(null, [Validators.required
            ]),
           'email': new FormControl(null, [Validators.required, Validators.email], this.forbiddenEmails),
           'password': new FormControl(null, [Validators.required,Validators.minLength(4)
            ]),
             'day': new FormControl(null, [Validators.required, Validators.maxLength(2),
             ]),
             'month': new FormControl(null, [Validators.required, Validators.maxLength(2)
             ]),
             'year': new FormControl('', [Validators.required, Validators.maxLength(4), Validators.minLength(4)
             ]),
         });
         this.SignupForm.setValidators(this.minimumAge(18));
       }
          private minimumAge(age: number): ValidatorFn {
            return (fg: FormGroup): ValidationErrors => {
              let result: ValidationErrors = null;
              if (fg.get('year').valid && fg.get('month').valid && fg.get('day').valid) {
                const value: { year: string, month: string, day: string } = fg.value;
                const date = moment({ year: +value.year, month: (+value.month) - 1, day: +value.day }).startOf('day');
                if (date.isValid()) {
                  const now = moment().startOf('day');
                  const yearsDiff = date.diff(now, 'years');
                  if (yearsDiff > -age) {
                    result = {
                      'minimumAge': {
                        'requiredAge': age,
                        'actualAge': yearsDiff
                      }
                    };
                  }
                }
              }
              return result;
            }
          }

    ngOnInit(): void {
    this.SignupForm.statusChanges.subscribe(res => if(status == 'VALID'){
    let day = this.SignupForm.get('day').value;
    let month = this.SignupForm.get('month').value;
    let year = this.SignupForm.get('year').value;
    let age = (new Date().getYear()-new Date(year,month,day,0,0,0).getYear());
}
}

    signupUser() {
      this.authService.registerUser(this.SignupForm.value).subscribe(
        data => {
          this.tokenService.SetToken(data.token);
          this.SignupForm.reset();
          setTimeout(() => {
            this.router.navigate(['posts']);
          }, 3000);
        },
        err => {
          if (err.error.msg) {
            this.errorMessage = err.error.msg[0].message;
          }

          if (err.error.message) {
            this.errorMessage = err.error.message;
          }
        }
      );
    }

Is there a way to extract the converted age value from this TypeScript function and send it to the database without using an age input field in the HTML?

Answer №1

Understanding Date Objects makes this task simple. Here's a single line of code that performs the magic:

console.log(new Date().getYear()-new Date(1995,12,17,0,0,0).getYear())

UPDATE:

Allow me to simplify it for you:

ngOnInit(): void {
    this.signUpForm.statusChanges.subscribe(res => if(status == 'VALID'){
    let day = this.signUpForm.get('day').value;
    let month = this.signUpForm.get('month').value;
    let year = this.signUpForm.get('year').value;
    let differenceInYear = (new Date().getYear()-new Date(year,month,day,0,0,0).getYear());
}
}

Utilize the variable differenceInYear in accordance with your logic.

Answer №2

From your comment, it seems like you are looking for validation along with the age data. To achieve this using your code, first, create a variable to store the date in that component.

export class YourSignupComponent implements OnInit {
 age: number
 // ..remaining code

If the function performs as expected, assign the age variable here:

if (yearsDiff > -age) {
// assign the new variable here
 age = yearsDiff;
 result = {
  'minimumAge': {
   'requiredAge': age,
   'actualAge': yearsDiff
  // ..remaining code

The concept is that the age variable will stay empty if someone is underage because the form can't be submitted without passing validation. However, it will contain the correct age if everything checks out. Now, retrieve this age variable and submit it to the backend as shown below.

signupUser() {
/* Once this is triggered, we'll have a valid form already,
 so set the variable in the form below and send it to the backend */
 this.SignupForm.age = age;
 this.authService.registerUser(this.SignupForm.value).subscribe(
  data => {
   this.tokenService.SetToken(data.token);
   // ..remaining code 

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

How to Show Concealed Text in Material UI Multiline TextField and Obtain Unveiled Text

I am currently using the Material UI TextField component to create a multiline input for messages. My aim is to display a masked version of the text in the GUI while retaining the unmasked text value for processing purposes. Below is the code snippet for ...

Extracting Date and Time Information from matDatepicker in Angular 6 Material

Below is the code snippet present in my html file: <mat-form-field> <input matInput [matDatepicker]="myDatepicker" placeholder="Choose a date" [(ngModel)]="model.value" name="value"> <mat-datepicker-toggle matSuffix [for]="myDatepic ...

Transforming JavaScript to TypeScript in Angular: encountering error TS2683 stating that 'this' is implicitly of type 'any' due to lacking type annotation

While in the process of migrating my website to Angular, I encountered an error when attempting to compile the JS into TS for my navbar. After searching around, I found similar issues reported by other users, but their situations were not quite the same. ...

What steps should I take to successfully launch an ASP.NET Core Angular Template without encountering any errors?

While working on a new ASP.NET Core 3.1 Angular Project using Visual Studio for Mac (v8.4.8) and running it in debug mode, I encountered an issue resulting in the following exception: "An unhandled exception occurred while processing the request Aggregat ...

Having trouble sending correct true/false values for selected radio buttons on an Angular5 table, often requiring users to click them twice to submit the appropriate values

My goal is to assign true or false values to selected radio buttons in each row and then form an object for submission. To distinguish between the radio button values in each row, I have used {{k}}+{{sizeobj.rbSelected}} as the value which is causing issue ...

Tips for converting a date string to a date object and then back to a string in the same format

I seem to be encountering an issue with dates (shocker!), and I could really use some assistance. Allow me to outline the steps I have been taking. Side note: The "datepipe" mentioned here is actually the DatePipe library from Angular. var date = new Dat ...

Implementing content projection or transclusion without the need for wrapper elements

Trying to include content inside a component (<parent>) with multiple <ng-content> slots but avoiding the need for a containing element for the child. This is necessary because the parent layout utilizes flexbox, and it's important to mak ...

Properties are determined by both the type and sub-type

A challenging TypeScript challenge. Exploring Multiple Discriminated Union Types This task involves intersecting multiple discriminated union types together, where there exists a relationship between "types" and their corresponding "sub-types." The Main Q ...

React input delay handling during onChange event

Upon closer inspection, I've come across an issue that I had not previously noticed. I am unsure if there is a bug within my code or if the onChange function always behaves in this manner, but I am experiencing input delay and am uncertain on how to r ...

Aframe failing to display image when using local path in Angular with AR.js

I am attempting to load an image from a local path within my Angular app component.html file. Below is the code snippet: <a-scene embedded arjs> <a-assets> <img id="test_img" src="/mnt/r/flipkart/proj/src/app ...

Assigning fields dynamically based on a generic string union concept

My goal is to create a function that can dynamically add fields and functions to an object based on arguments provided. However, I'm encountering an issue where the function does not recognize the types of these dynamic fields. Here's a simple ex ...

What is the recommended version of Node to install in order to have Angular CLI support?

As a beginner in development, I recently started experimenting with Angular and after successfully installing everything with "npm install -g @angular/cli", I encountered an error when running "ng version". Can someone provide guidance on this issue? I at ...

Tips for enhancing the appearance of the dropdown scrollbar in PrimeNG

Just started exploring Angular and I've been struggling to customize the scrollbar on a PrimeNG dropdown. Does anyone have any tips or tricks to achieve this? Here is the HTML code: <p-autoComplete placeholder="- Select -" (onSelect)="onSelect(dh ...

`Angular 6 data table server-side AJAX call issue persists`

Currently utilizing angular datatable version 1.10.19. You can check this out for the server-side Angular approach I have developed a web API in C# to fetch data in the desired format. The server side functionality is working smoothly with the following d ...

Tips for setting variable values in Angular 7

I'm encountering an issue with assigning values to variables in my code. Can anyone provide assistance in finding a solution? Here is the snippet of my code: app.component.ts: public power:any; public ice:any; public cake:any; changeValue(prop, ...

Tips for customizing the appearance of the initial React component frame

While working on my app's loading screen, I noticed a brief moment when a blank white page appears. Even the default React app displays this issue, but interestingly, it does not occur on platforms like Stack Overflow. This wouldn't be a concern ...

Tips for configuring the navigation links on the current page using Bootstrap

In my Angular application, I have set up navigation links for home, about, notifications, and logout. However, when I click on the home link, it redirects me to the login page instead of remaining on the current page. I need the functionality to stay on ...

Unveiling typescript property guards for the unknown data type

Is there a way to type guard an unknown type in TypeScript? const foo = (obj: unknown) => { if (typeof obj === 'object' && obj) { if ('foo' in obj && typeof obj.foo === 'string') { r ...

Making sure to consistently utilize the service API each time the form control is reset within Angular 4

In the component below, an external API service is called within the ngOnInit function to retrieve an array of gifs stored in this.items. The issue arises when the applyGif function is triggered by a user clicking on an image. This function resets the For ...

Ways to retrieve sorted and updated items in ngx-datatable post-sorting

I am currently utilizing the swimlane/ngx-datatable library to display a list. Within each row of the list, I have implemented an action menu that pops up upon clicking an icon, with dynamically generated items. Challenge: Following sorting, the items app ...