Angular typescript: Determine the range of numbers

I'm currently working on a project using Ionic and Angular, and I'm facing the challenge of creating a select dropdown with a specific range of numbers. However, manually inputting these numbers is not efficient, so I'm looking for a way to generate them dynamically in TypeScript.

In the "ages" variable, I aim to have the numbers generated as selectable options for the dropdown.

Here is the TypeScript file code snippet:

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-user-appearance',
  templateUrl: './user-appearance.component.html',
  styleUrls: ['./user-appearance.component.scss']
})
export class UserAppearanceComponent {
  appearanceForm = new FormGroup({
    age: new FormControl(''),
    height: new FormControl(''),
    weight: new FormControl(''),
    ethnicity: new FormControl(''),
    eyesColor: new FormControl(''),
    hairLength: new FormControl(''),
    hairColor: new FormControl('')
  });

  ages: number[] = [1,2,3,4,5,6,7,8,9,10];
  constructor() { }

  submit() {
    console.log(this.appearanceForm.get('age').value);
  }
}

And here is the corresponding HTML code:

<ion-header>
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-back-button text="{{'back' | translate}}"></ion-back-button>
    </ion-buttons>
  </ion-toolbar>
</ion-header>

<ion-content class="ion-padding">
  <h1>{{'letUsKnowHowYouLook' | translate}}</h1>
  <h3>{{'easyToIdentifyYou' | translate}}</h3>

  <form [formGroup]="appearanceForm" (ngSubmit)="submit()">
    <ion-item >
      <ion-label>{{'age' | translate}}</ion-label>
      <ion-select placeholder='{{"selectOne" | translate}}' formControlName="age">
        <ion-select-option *ngFor="let age of ages">{{age}}</ion-select-option>
      </ion-select>
    </ion-item>
    <app-input [label]="'height'| translate" formControlName="height"></app-input>
    <app-input [label]="'weight'| translate" formControlName="weight"></app-input>
    <app-input [label]="'ethnicity'| translate" formControlName="ethnicity"></app-input>
    <app-input [label]="'eyesColor'| translate" formControlName="eyesColor"></app-input>
    <app-input [label]="'hairLength'| translate" formControlName="hairLength"></app-input>
    <app-input [label]="'hairColor'| translate" formControlName="hairColor"></app-input>


    <ion-button expand="block" type="submit" >{{'confirm' | translate}}</ion-button>
  </form>
</ion-content>

Answer №1

Make sure to use this one.

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';

@Component({
 selector: 'app-user-appearance',
 templateUrl: './user-appearance.component.html',
 styleUrls: ['./user-appearance.component.scss']
})
export class UserAppearanceComponent {
 appearanceForm = new FormGroup({
  age: new FormControl(''),
  height: new FormControl(''),
  weight: new FormControl(''),
  ethnicity: new FormControl(''),
  eyesColor: new FormControl(''),
  hairLength: new FormControl(''),
  hairColor: new FormControl('')
});

ages: number[];
constructor() {
 const range = (start, end) => Array.from({ length: (end - start) }, (v, k) => k + start);
 this.ages = range(1, 11);
}

submit() {
 console.log(this.appearanceForm.get('age').value);
 }
}

The important thing is to include a range in the constructor definition.

ages: number[];
constructor() {
 const range = (start, end) => Array.from({ length: (end - start) }, (v, k) => k + start);
 this.ages = range(1, 11);
}

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

JavaScript - Employing the .every function with an array containing objects

Is it possible to use the array.every method on multidimensional arrays? The structure of my array is as follows: tabs=[ {label: string, icon: icon, routerLink: link}, {label: string, icon: icon, routerLink: link}, {label: string, icon: icon, routerLink: ...

What is the best way to invoke a function from a Service to a Component in Angular?

Currently, I am in the process of learning Angular and recently created an alarm clock feature. In this functionality, users have the option to select alarms they wish to cancel by using checkboxes that are then stored in local storage through the use of & ...

Utilizing session variables across multiple TypeScript files

There is a session variable called session in my home.component.ts. I need to access this variable in both user.compnent.ts and dashboard.component.ts. This is how the session variable is defined in home.component.ts: var session = sessionStorage.getIte ...

Angular 5: Issues with retrieving response using HttpClient's get request

Alright, so typically I work with Angular 1.*, but I decided to dive into Angular 5 and man, it's been a bit of a challenge. It feels unnecessarily complex, but oh well... So I'm trying to make an HTTP call, and I have this node API that is retu ...

Design: Seeking a layout feature where one cell in a row can be larger than the other cells

To better illustrate my goal, refer to this image: Desired Output <\b> Currently, I'm achieving this: current output Imagine 7 rows of data with two columns each. The issue arises in row 1, column 2 where the control needs to span 5 row ...

What steps can be taken to access our Angular application via URL after deploying it on the Azure cloud platform?

My Angular app has been successfully deployed on Azure and is currently running. However, I am unsure of how to access it through my browser. The application is running on the default port 4200. Can anyone provide guidance on any necessary configurations ...

items within an unordered list that can be collapsed

Answer: Nikhil was on the right track with his solution, but I had to make some modifications. Specifically, I needed to create and initialize an empty array to display the details properly. Here's the updated code: if (this.name.toLowerCase() == va ...

Create a new map in Typescript by initializing it with an array: `new Map([[key1, value1], [key2, value2]])

Do these two initializations differ in functionality? The following code snippet works as expected: private screensMap: Map<string, ComponentType<any>>; public constructor() { this.screensMap = new Map() .set(BootstrapLaunch.name ...

Are reflection problems a concern when using type-graphql mutations?

Recently, I've been experimenting with integrating type-graphql into my nodejs project. While implementing @Query methods went smoothly, I'm facing challenges with the following code snippet in combination with Moleculer service. @Mutation() / ...

Tips for removing characters from a string and determining the number of characters that are left

I am working with a string that I want to slice 22 characters from the beginning and then determine the count of remaining characters. For example - Red, Blue, ABC, Test1, REN, Green, Test, Red - Total 37 characters Desired Output: Red, Blue, ABC, Test1 ...

Implementing Material UI using TypeScript

I recently started using TypeScript and the OnePirate premium theme from materialUI. I encountered an issue when trying to implement the Footer component in my project by renaming it to .tsx file. The error message displayed was "No Overload matches this c ...

Error in TypeScript logEvent for Firebase Analytics

Currently utilizing firebase SDK version 8.0.2 and attempting to record a 'screen_view' event, encountering an error message stating: Error: Argument of type '"screen_view"' is not assignable to parameter of type '" ...

What is the best way to pass a string value instead of an event in Multiselect Material UI?

Greetings, currently utilizing Material UI multi select within a React TypeScript setup. In order to modify the multi select value in the child component, I am passing an event from the parent component. Here is the code for the parent component - import ...

There seems to be an issue with a potentially null object in an Angular project while trying to view a PDF file

IDENTIFY THE ERROR: printContents = document.getElementById('print').innerHTML.toString(); ON LINE 4: print(): void { let printContents!: string; let popupWin!: any; printContents = document.getElementById('print').innerHTM ...

Mastering the art of utilizing Function's construct signatures within TypeScript

Currently delving into the TypeScript documentation, specifically exploring More on Functions. However, I find myself perplexed by the code snippet provided below. Can someone offer guidance on how to implement this in practical development scenarios? An ...

Angular - Automatically create thumbnails for uploaded images and videos

I am working on an Angular application that allows users to upload files. My goal is to create thumbnail images for uploaded images and videos without saving them locally. Instead, I plan to pass them along with the original file data to another API. Howev ...

In React TS, the function Window.webkitRequestAnimationFrame is not supported

I'm facing an issue where React TS is throwing an error for window.webkitRequestAnimationFrame and window.mozRequestAnimationFrame, assuming that I meant 'requestAnimationFrame'. Any suggestions on what to replace it with? App.tsx import Re ...

Allow exclusively certain type to pass through the function

Is it possible to receive an error message from the function in the following example? I have included comments at a relevant spot in the code below: interface Pos { x: number, y: number, } function doSome(pos: Pos) { return pos.x + pos.y } let p ...

Automatically adjust the position of the marker popup if it is near the edge of the map container in @react-google

I am currently working on adjusting the position of markers' popup windows based on their proximity to the edge of the map container. The issue arises when the popup is hidden under the container if the marker is near the edge. One example that impl ...

Issue with callback function causing incorrect type inference

Here is a simplified code snippet: interface Store<T> { value: T } type AnyStore = Store<any> type StoreValue<T> = T extends Store<infer V> ? V : never function computed< V, D extends AnyStore, S extends Store<V> ...