locnguyen
locnguyen

Reputation: 841

Angular 2 declaring dynamic property inside component

I want to declare some properties inside the component like so

export class HeroComponent implements OnInit {

    hero1:
    hero2:
    hero3:
    hero4:
    ...
    hero999:

}

Is there a better way to declare these properties instead of writing them all out?

Upvotes: 2

Views: 1552

Answers (2)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657426

export class HeroComponent implements OnInit {
  heroes: any[] = [];

  constructor() {
    for(var i = 1; i < 1000; i++) {
      this.heroes.push('hero'+i);
    }
  }
}

Upvotes: 2

Ashwin Kumar
Ashwin Kumar

Reputation: 741

A cleaner way to write properties is to take advantage of typescript interfaces. You can define the options that are permitted in the interface and use it similar to this:

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[]
}

Upvotes: 0

Related Questions