0

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() {

  }

}

2 Answers 2

1

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);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I have tried this way. But It does not call the constructor of Passenger.
So you need to add Passenger objects into the array. You can do like ebove
1

Call the constructor from within a map:

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

2 Comments

this won't work.new Array will generate a array with empty slots and they will be ignored in map
@Austaras I did not know that. Thanks! Updated my answer for what it's worth.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.