简体   繁体   中英

Initializing an array of class with certain number of elements in Angular

I am looking for a way to initialize an array of type Passenger which its number of elements is equal to the value of variable count . How can I do it in ngOnInit() ???

This is 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 = ''
    ) { }
}

And this the content of home.component.ts :

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


export class HomeComponent implements OnInit {

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


  constructor() { }

  ngOnInit() {

  }

}

Do you mean something like that?:

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

To add empty Passenger objects:

passengers: Passenger[] = [];

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

Call the constructor from within a map:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM