I am trying to practice Typescript and ran into an issue that seems to either be an Angular problem or I'm at least getting conflicting feedback
In my Angular view, I am trying to loop over a static array of fighters in a class Roster
. Here is the class definition:
export class Roster {
static Fighters: Array<Fighter> = [
...
]
}
In my view, I am trying to loop over the predefined Fighter
s with:
<ng-container *ngFor="let fighter of Roster.Fighters; let i = index">
However I get an error here, with the message:
Property 'Fighters' does not exist on type 'Roster'. Did you mean to access the static member 'Roster.Fighters' instead?ngtsc(2576)
This is confusing because of already accessed the fighters array in the class itself, here's the other member of my Roster
class
export class Roster {
static fighterLookup(fighterId: number): Fighter {
console.log(Roster.Fighters[fighterId]);
}
...
}
And in my component, I've simply assigned a Roster variable to the class definition:
export class AppComponent {
Roster: Roster = Roster;
}
So I can access the list of fighters with Roster.Fighters
in the typescript file but I can't do so in the ngFor loop? What am I missing? Do I need to define it some other way in my component to be able to access the static array?
CodePudding user response:
The main reason of such behavior is because in typescript class you always has access to static method by the name of the class (It's Roster
in your case), it's part of javascript language
In the angular template you don't have access to class itself, just instance of this class(it's like new Roster
all the time)
In this case you can add some getter to the class:
export class Roster {
static Fighters: Array<Fighter> = [
...
]
get FightersView() {
return Roster.Fighters;
}
}