我想在组件中声明一些属性,如此
export class HeroComponent implements OnInit {
hero1:
hero2:
hero3:
hero4:
...
hero999:
}
有没有更好的方法来声明这些属性而不是全部写出来?
答案 0 :(得分:2)
export class HeroComponent implements OnInit {
heroes: any[] = [];
constructor() {
for(var i = 1; i < 1000; i++) {
this.heroes.push('hero'+i);
}
}
}
答案 1 :(得分:0)
编写属性的一种更简洁的方法是利用typescript接口。 您可以定义界面中允许的选项,并使用与此类似的选项:
export class HeroComponent implements OnInit {
private options: Options
constructor() {
this.options = {
option1 : 'val1',
option3 : [1,2]
}
}
}
export interface Options {
option1: string,
option2?: boolean,
option3: number[]
}