Limit the number of years shown in the dropdown menu to verify that the user is at least 18 years old

I have a dropdown for selecting the year on my form, where the user will enter their date of birth.

My goal is to determine how many years I should display in the dropdown to ensure the person is at least 18 years old.

Currently, I am calculating this by subtracting 18 years from today's date, which brings me back to 1999. This way, I can confirm that the user is indeed 18 years or older.

getYears() {

    var ageRestriction: number = 18;
    var now = new Date();
    var thisDate = (now.getFullYear() - 18);

   // Now, I want to show the years before 1999 i.e 1998, 1997, 1996, 1995 etc

}

Next, I need to loop through and display 60 years prior to 1999:

1999, 1998, 1997, 1996, 1995, 1994 and so on

I'm struggling to figure out the syntax for achieving this, hence why I am asking this question.

If anyone can demonstrate how to accomplish this task or suggest a more efficient way of handling it, please feel free to share your knowledge with me :)

Answer №1

Here is the method I would personally choose to tackle this issue.

years: number[] = [];
setYears() {
    const ageRequirement = 18;
    const datetime = new Date();
    const maximumYear = (datetime.getFullYear() - ageRequirement);
    const minimumYear = (maximumYear - 61);

    for (let i = maximumYear; i >= minimumYear; i--) {
        this.years.push(i);
    }
}

There may be a more sophisticated solution available, but this one accomplishes the task at hand. My assumption is that you prefer the list to be sorted in descending order (from the most recent year to the oldest).

I hope this information proves helpful to you.

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

Issue with utilizing Lodash's _.findIndex method while installing lodash through tsd and saving it in an Angular2 project

I have successfully incorporated lodash in two different methods: Method 1: I installed it in bower_component and added declare var _:any; in components. It's working perfectly. Within a click event, I am calling this function: checkLodash() { _.f ...

Ways to limit the type based on the value of the argument

Is it possible to narrow down the type of the library in the demo code provided? Can we use the factory function to create a new function fnP with an exact type instead of any? const libOne = { p: () => 0, q: () => 1, }; const libTwo = { x: ( ...

Tips for simulating localStorage in TypeScript unit testing

Is there a method to simulate localStorage using Jest? Despite trying various solutions from this post, none have proven effective in TypeScript as I continue encountering: "ReferenceError: localStorage is not defined" I attempted creating my ...

I encountered a warning while using the useViewportScroll in NextJs with Framer Motion: "Caution: The useLayoutEffect function does not have any effect on the server

Successfully implementing NextJs with Framer Motion, yet encountered a warning: Warning: useLayoutEffect does not function on the server due to its effect not being able to be encoded in the server renderer's output format. This may cause a differenc ...

Utilizing Typescript and Jest to prevent type errors in mocked functions

When looking to simulate external modules with Jest, the jest.mock() method can be utilized to automatically mock functions within a module. After this, we have the ability to modify and analyze the mocked functions on our simulated module as needed. As ...

Issue with Angular 10: Modal window fails to open upon second click

Encountering an issue with a Modal window overlapping the navigation bar and overlay due to a third-party bundle.js adding dynamic classes and divs under the parent-container. The problem arises from a fixed positioning of one of the classes which causes t ...

In Angular2, you can dynamically show or hide previous and next buttons based on the contents of the first and last div

I need a solution to dynamically hide or show previous and next buttons based on the div tags created. Each value in a list is being used to generate individual div tags using ngFor loop in Angular 2. The list being utilized is: appUlist:string[] = ["Cal ...

What is the best type to use for an Angular component?

I attempted to pass a concrete component to a dialog: public openDialog(dialogModel: IDialog, component: any): Observable<boolean> { let dialogRef = this.dialog.open(component, { disableClose: true, panelClass: dialogModel.settings.c ...

Exploring the use of TypeScript and Webpack to read non-JavaScript files in Node.js

I'm working on a backend NodeJS setup written in TypeScript that is using webpack for compilation. However, I encountered an error when trying to read a text file even though I confirmed that the file source/test.txt is being copied to the build fold ...

Issue with file uploading in Angular 9 as the uploaded file is not being added to the

I've set up a form group in the HTML of my Angular 9 app that includes an upload feature for files. The file upload works fine when calling the handleFileInput function, as I can confirm from the console log output. However, even though the file gets ...

Transform a group of objects in Typescript into a new object with a modified structure

Struggling to figure out how to modify the return value of reduce without resorting to clunky type assertions. Take this snippet for example: const list: Array<Record<string, string | number>> = [ { resourceName: "a", usage: ...

Is Node.js and Express.js necessary when utilizing Angular2 in development?

A web application prototype was developed using the following technologies: Angular 2 TypeScript ASP.Net WebAPI 2 Mongo DB Karma/Jasmine Node.js (solely as a server, in accordance with Angular2 Quick Start instructions) Given the tech stack mentioned ab ...

Monitor the true/false status of each element within an array and update their styles accordingly when they are considered active

Currently, I am attempting to modify the active style of an element within an array. As illustrated in the image below - once a day is selected, the styles are adjusted to include a border around it. https://i.stack.imgur.com/WpxuZ.png However, my challe ...

Is it possible for ngModelChange to function with a custom form control?

Suppose I want to create a custom form control. Is it possible to achieve this? <custom-control [ngModel]="myModelVariable" (ngModelChange)="modelHasChanged($event)"></custom-control> I've successfully implemented [(ngModel)] with all th ...

Error encountered due to a circular reference in the dependency library

Whenever I attempt to run my application, I encounter the following error: > npm start Starting the development server... ts-loader: Using <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="42363b32273121302b323602716c776c71"& ...

Storing input values in the state using Typescript by default

Upon launching, my activeField state is initially empty. However, when a user focuses on the field, it gets added to the state. I am encountering a warning in Typescript because when I attempt to update the selectionEnd of that field, it tells me: Property ...

Deactivate the input fields within a dynamic form

I have already attempted to follow the solutions provided in other responses here, but unfortunately, I have not been successful! I have developed a dynamic reactive form and I am looking to disable certain fields at specific times. Below is my form code: ...

Is there a way to prevent Intellij from constantly compiling TypeScript at a very slow pace?

In the process of transitioning my Angular 1.x project from vanilla JS to TypeScript, I'm encountering frustratingly slow response times from my IDE.https://i.sstatic.net/LkiDj.png When I uncheck "Track changes" in Settings > Languages & Framework ...

Using ngFor to iterate through an array of objects in Angular 5

Here is the class structure I am working with: export class CarsData { public PrimaryCars: string[]; public SecondaryCars: string[]; } export class Cars { public CarsInfo: Array<CarsData>; } I am trying to use ngFor directive o ...

Display database information on the webpage

I've been attempting to display information from my database on an HTML page but it doesn't seem to be working. Below is the code snippet from my HTML file. The database is named softball_leagues and the table is called players, referred to as th ...