我正在尝试在我的NativeScript Angular项目中使用* ngFor,但总是收到一个错误消息,
错误:错误{
所以我很困惑,不知道自己哪里出了问题。
这是我的模特,leagues.ts
:
export class Leagues {
leagueName: string;
totalLeagueSize: number;
currentLeagueSize: number;
schoolID: string;
leagueClass: string;
}
在这里我在leagues.component.ts
中声明它:
public leagues: Leagues;
ngOnInit(): void {
this.leagues =
{
"leagueName": "Basketball",
"totalLeagueSize": 20,
"currentLeagueSize": 18,
"schoolID": "AAA",
"leagueClass": "basketballClass"
},
{
"leagueName": "Football",
"totalLeagueSize": 14,
"currentLeagueSize": 14,
"schoolID": "AAA",
"leagueClass": "footballClass"
},
{
"leagueName": "Soccer",
"totalLeagueSize": 9,
"currentLeagueSize": 10,
"schoolID": "AAA",
"leagueClass": "soccerClass"
},
{
"leagueName": "Volleyball",
"totalLeagueSize": 8,
"currentLeagueSize": 10,
"schoolID": "AAA",
"leagueClass": "volleyballClass"
},
{
"leagueName": "Dodgeball",
"totalLeagueSize": 8,
"currentLeagueSize": 10,
"schoolID": "AAA",
"leagueClass": "dodgeballClass"
},
{
"leagueName": "Softball",
"totalLeagueSize": 4,
"currentLeagueSize": 5,
"schoolID": "AAA",
"leagueClass": "softballClass"
};
}
然后在这里将其保存在leagues.component.html
中:
<Button *ngFor="let league of leagues" [ngClass]="league.leagueClass" [text]="league.leagueName" style="width: 95%; height: 15%; margin-top: 2%;" ></Button>
任何帮助将不胜感激,谢谢!
答案 0 :(得分:1)
有两件事在您的代码中不正确。 首先,您必须使用interface定义对象。
您所用的正确方法是:
export interface Leagues {
leagueName: string;
totalLeagueSize: number;
currentLeagueSize: number;
schoolID: string;
leagueClass: string;
}
第二种初始化数组的方式。 应该用方括号内的对象完成。
示例:
public leagues:Leagues[];
this.leagues = [
{
"leagueName": "Football",
"totalLeagueSize": 14,
"currentLeagueSize": 14,
"schoolID": "AAA",
"leagueClass": "footballClass"
},
{
"leagueName": "Soccer",
"totalLeagueSize": 9,
"currentLeagueSize": 10,
"schoolID": "AAA",
"leagueClass": "soccerClass"
}
]