I'm struggling to figure out the age calculation in my Angular 2 code. Every time I try to run it,

Can anyone assist me with calculating age from a given date in Angular? I have written the following code but I keep getting undefined in the expected field.

This is Component 1

import {
  Component,
  OnInit,
  Input
} from '@angular/core';
import {
  DatosDTO
} from '../../dto/datos'

@Component({
  selector: 'app-datos-personales',
  templateUrl: './datos-personales.component.html',
  styleUrls: ['./datos-personales.component.css']
})
export class DatosPersonalesComponent implements OnInit {
  @Input()
  datosDTO: DatosDTO;

  public age: number;

  constructor() {}

  ngOnInit() {
    this.datosDTO = new DatosDTO();
  }
  CalculateAge(): void {
    if (this.datosDTO.datosPersonales.fechaNacimiento) {
      var timeDiff = Math.abs(Date.now() - this.datosDTO.datosPersonales.fechaNacimiento);
      this.age = Math.ceil((timeDiff / (1000 * 3600 * 24)) / 365);
    }
  }
}
This is the DatosPersona class
export class DatosPersona {
  tipoIdentificacion: string = "";
  numeroIdentificacion: string = "";
  nombres: string = "";
  apellidos: string = "";
  fechaNacimiento: number;
}

This is the HTML template

<div class="row">
  <div class="small-6 columns">
    <label>Age</label>
  </div>
  <div class="small-2 columns">
    <input readonly type="text" [value]="CalculateAge()">
  </div>
</div>

Your assistance would be greatly appreciated.

Answer №1

Ensure to specify a return type for your method

CalculateAge(){
    if (this.datosDTO  && this.datosDTO.datosPersonales.fechaNacimiento) {
      var timeDiff = Math.abs(Date.now() - this.datosDTO.datosPersonales.fechaNacimiento);
      this.age = Math.ceil((timeDiff / (1000 * 3600 * 24)) / 365);
      return this.age;
    } else {
      return '';
    }

  }

Additionally, make sure to treat your object fechaNacimiento as a date object. You can achieve this by using the following method

var timeDiff = Math.abs(Date.now() - 
     Date.parse(this.datosDTO.datosPersonales.fechaNacimiento));

Remember that the datosDTO object may be undefined at the beginning. Therefore, including a check for it will address your issue

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 is the best way to change the `this` type of an object that is provided as a parameter to a function

I am looking to create a custom function that can expose certain properties to the this of an object being passed as an argument. For example, this is how the function would be called: const props = ['bar']; myBarFunction(props, { get foo() { ...

The EventEmitter in Angular 8 is prohibiting the emission of an Object

Is there a way I can emit an Object instead of primitive data types? I have an object const amount = { currenty: 'USD', total: '10.25' }; that I need to emit to the parent component. export class MyChildComponent implements OnInit { ...

Is it possible to utilize a FOR loop in TypeScript to store an array in a variable?

Hey there pals! I could really use your brain power for a solution that requires some context. Our array ress is limited to items that meet a certain condition. After filtering the array, I need to store the new results in a different variable. I' ...

Tips for tracking the evolution of changes to an array within React State

Experiencing challenges with saving the history of updates and modifications on a State. I have an object called "Journey" which includes a list of workshops (another array). Whenever I update my list of workshops, I aim to create a new array that captures ...

Utilizing Typescript for constructor parameter assignments

Within my codebase, there exists an interface: export interface IFieldValue { name: string; value: string; } This interface is implemented by a class named Person: class Person implements IFieldValue{ name: string; value: string; const ...

Attempting to connect to "http://localhost:4242/webhook" was unsuccessful due to a connection refusal when trying to dial tcp 127.0.0.1:4242

In my next.js 13 project, I am integrating stripe with TypeScript and configuring the app router. To create a stripe event in my local machine, I ran stripe listen --forward-to localhost:4242/webhook, but now I am encountered with the error message stripe ...

When using RxJS forkjoin, it will cease subscription if there is a flatMap present within one of the observables it is awaiting

I have been experimenting with nested calls using rxjs and trying to implement nested forkJoins. However, I have encountered an issue where the outer forkJoin stops returning a result when there is a flatMap inside the inner observable. Here is a snippet ...

Guide to building a nested dropdown navigation in Angular 12 with the power of Bootstrap 5

I am looking to implement a multilevel dropdown feature in my Angular 12 project with Bootstrap 5. Can someone please guide me on how to achieve this? For reference, you can view an example here. Thank you in advance! ...

Confirm that the input field in Angular 5 has a default value before proceeding with validation

My form contains an input field with a default value. I am looking to add validation to ensure that the field has exactly 5 characters. <td> <input type="text" maxlength="5" ngModel #number="ngModel" name="number" value="{{data.number}}" ...

What could be causing the malfunction of the Bootstrap5 modal hide feature?

Today, I am facing an issue with hiding the Bootstrap5 modal in a TypeScript function. Despite trying to invoke the hide function on the modal element, it does not work as expected. Here is the minimal code snippet to reproduce this problem: import React f ...

What is the proper way to bring in Typescript types from the ebay-api third-party library?

My TypeScript code looks like this: import type { CoreItem } from 'ebay-api'; declare interface Props { item: CoreItem; } export default function Item({ item }: Props) { // <snip> } However, I encounter an issue when trying to build ...

What is the best way to include a string index signature in a preexisting Array?

Currently, I am immersed in styled-system and attempting to define a pattern that is frequently employed within the library. const space: { [key: string]: string } = [ '0.25rem', '0.5rem', '1rem', '2rem', ...

Variety of part ingredients

In my component, I have a button and include another component which also contains a button. How can I align these two buttons next to each other without using absolute positioning? When I try positioning them using absolute right and top values, the lay ...

Exploring Typescript keyof in Storybook's User Interface customizations

Currently, I am working on developing components for integration with Storybook, but I am encountering an issue related to Typescript inferred types. While striving for code reusability, I prefer not to specify the options for a control within the story i ...

Tips for updating the front end with the status of a lengthy playwright test

In the node backend, I have defined a route for test progress using SSE (https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events). The URL initialization is happening on the frontend. Below is the code snippet from th ...

Interacting with a Web Socket Connection While Editing Inline Content Causes Distractions. Using Angular 9 Material Table

Not exactly an error-related inquiry, but more about behaviors. In my Angular 9 setup using RxJS and Material, I have a table connected to a web socket for updates triggered by blur or change, depending on the column. This setup works well, updating the ta ...

The selected value of the PrimeNG p-checkbox cannot be determined using a function when binding to [ngModel]

These are the rows of my custom p-table <tr> <td>{{user.userName}}</td> <td>{{use.userSurname}}</td> <td *ngFor="let group of groups"><p-checkbox [(ngModel)]="showVal ...

Where is the best place to obtain the clientSecret key for mounting Stripe elements?

UPDATED CODE Hello, I am looking to integrate Stripe for user subscriptions. I'm unsure about the client Secret key in my setup. I am using Ionic 5 with Angular 14 and Capacitor 5, along with PHP as the backend. In my implementation, I used PHP to ...

Tips for creating React/MobX components that can be reused

After seeing tightly coupled examples of integrating React components with MobX stores, I am seeking a more reusable approach. Understanding the "right" way to achieve this would be greatly appreciated. To illustrate my goal and the challenge I'm fac ...

Guidelines for transitioning an AngularJS module for injection into an Angular 2 component

After diving into the Angular 2 upgrade guide and successfully setting up a hybrid app (combining ng1 as a base code with components and services gradually transitioning to ng2), I've hit a snag. How do I incorporate 3rd party ng1 modules so that Angu ...