[英]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
.我在寻找一种方法来初始化类型的数组Passenger
其中其元件的数目等于变量的值count
。 How can I do it in ngOnInit()
???我怎样才能在ngOnInit()
做到这ngOnInit()
???
This is the Passenger
model:这是Passenger
模型:
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
:这是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());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.