Creating a class array with a specific number of elements in Angular

Is there a way to initialize an array of type Passenger with a number of elements equal to the value stored in the variable count, all within the ngOnInit() function?

Here is the definition of the Passenger model:

export class Passenger {
    constructor(
        public ageCategory: string = '',
        public name: string = '',
        public lastName: string = '',
        public Ssn: string = '',
        public birtDate: NgbDate = new NgbDate(0, 0, 0),
        public passportDate: NgbDate = new NgbDate(0, 0, 0),
        public gender: string = '',
        public passportCountry: string = ''
    ) { }
}

Below is the code snippet from home.component.ts:

import { Passenger } from '../../models/passenger';


export class HomeComponent implements OnInit {

  passengers: Passenger[];
  count: number = 5;


  constructor() { }

  ngOnInit() {

  }

}

Answer №1

Are you suggesting something like this?:

ngOnInit() {
    this.passengers = new Array<Passenger>(3);
}

To populate with empty Passenger objects:

passengers: Passenger[] = [];

ngOnInit(){
    for(let i=0;i<this.count;i++){
        let pass= new Passenger();
        this.passengers.push(pass);
    }
}

Answer №2

To create new Passenger objects, you can utilize the constructor within a map method like so:

ngOnInit() {
  this.passengers = new Array(this.count)
    .fill(0)
    .map(_ => new Passenger());
}

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

I'm unsure how to utilize the generic type in this particular scenario. It's a bit confusing to me

Recently, I delved into TypeScript generics and applied them in specific scenarios. However, I encountered some challenges. While working with two different interfaces, I faced a need for flexibility. For instance, I needed to make server requests. func ...

The parent-child relationships in MongoDB

In my Meteor application, I have created two collections: ActivityCards and Users. Inside the ActivityCard collection, there is a reference to the User like this: { "_id" : "T9QwsHep3dMSRWNTK", "cardName" : "Guntnauna", "activitycardType" : 1 ...

Organize the HTML output generated by a PHP array

There must be a simple solution to this, but for some reason, it's escaping me right now. I've created custom HTML/CSS/JS for a slider that fetches its content from an array structured like this: $slides = [ [ 'img' = ...

Personalize the start and end dates of Fullcalendar

While working with fullcalendar, I have a unique requirement. I want my days to start at 5:00 and end at 5:00 the next day. Is it feasible to achieve this customization? ...

Setting a pre-selected value in a Vue.js dropdown list involves a few simple steps. This

Currently, I am developing two Vue components. I am sending array data from the parent component to the child component using props. Now, I have a requirement to pre-select a value in the dropdown list of the child component. Below is a snippet of my code ...

Angular 2 - The constructor of a class cannot be called without using 'new' keyword

Currently, I am working on integrating the angular2-odata library into my project. This is the code snippet I have: @Injectable() class MyODataConfig extends ODataConfiguration { baseUrl = "http://localhost:54872/odata/"; } bootst ...

"Utilize JavaScript to detect both the loading and unloading events on a webpage

I attempted to capture the window.open onload and onunload events. The issue arises when I use URLs from other domains. For example: When the URL is for the same page, both events trigger as desired. window.open("/") View PLUNKER with same page URL .. ...

The JavaScript else statement is failing to execute as intended

Hello, I am new to JavaScript and could really use some assistance. In the code snippet below, I am having trouble with the logic for the submit button. The line _btn.addEventListener seems to be causing an issue where only the "if" part is being executed ...

Storing the output of asynchronous promises in an array using async/await technique

I am currently working on a script to tally elements in a JSON file. However, I am encountering difficulty in saving the results of promises into an array. Below is the async function responsible for counting the elements: async function countItems(direct ...

Building a search form using Vue.js with query parameters

Incorporating Vue.js 2.6 with the vue-router component has been quite a journey for me. My search form setup looks like this: <form class="search-form" @submit.prevent="search"> <div class="form-group"> <input type="text" class= ...

Creating an infinite SVG animation loop using JavaScript

elem = document.querySelectorAll("path"); function task(i) { setTimeout(function() { elem[i].animate({fill: 'green'}, { // timing options duration: 150, iterations: 1 }); }, 150*i); } for(var i=0;i<8;i++){ task(i); } < ...

Is there a way to track and detect alterations to an element using JavaScript or jQuery

Can I detect the addition of a specific CSS class to an element without having to create a new event? ...

Developing applications using ReactJS with Typescript can sometimes lead to errors, such as the "onclick does not exist on type x

In the code snippet below, I have a method that renders a delete icon and is used in my main container. Everything functions correctly except for a small cosmetic issue related to the type any that I am struggling to identify. import React from 'reac ...

Is there a permanent solution to fixing the error code -4094 that is repeatedly occurring during React Native startup?

When attempting to execute react-native start, an error occurred which has not been encountered before. The error message is as follows: ERROR ENCOUNTERED Loading dependency graph...events.js:287 throw er; // Unhandled 'error' event ...

Utilize Auth.currentSession() every 5 minutes within Vuex Store for automatic session management

I have been developing an application that makes frequent requests to our API, however, sometimes these requests result in expired tokens. I have explored different solutions such as calling Auth.currentSession and setting the header before sending the re ...

Struggling to get Angular to properly sanitize inputs using ng-bind-html

I've been struggling to figure out the issue in my code for an entire day with no success. At this point, I'm reaching out for help. My problem arises when trying to utilize ng-bind-html-unsafe within a template. As a newcomer to Angular, it&apos ...

HTML Element Split in Two by a Line in the Middle

Greetings to all, after observing for a while I have decided to make my first post here (and just to clarify, I am an electrical engineer, not a programmer). I am in search of creating a unique element in HTML where I can detect clicks on both its upper a ...

Transfer or duplicate an SVG image from the bottom div to the top div

Is there a way to move a div from the chart_div to the movehere div? I've tried duplicating it below the current svg, but I'm having trouble targeting just the header row ('g' element) specifically. Here is the HTML: <script type= ...

tips for deactivating routerLink functionality on anchor elements

Working on an Angular application that requires me to create an image slider. However, due to the presence of router links in the application, the anchor tags in the image slider keep redirecting. I want to prevent this redirection and instead successful ...

Creating separate chunks for individual files in Vue CLI3JsonPropertyTitleFileType

I am working on a project using vue-cli3 and need to separate out a specific file for chunking due to IIS requirements. Currently, webpack chunks files based on default settings and also automatically creates chunks from dynamic imports in vue-router. How ...