【发布时间】:2019-04-19 11:02:10
【问题描述】:
我正在开发一个 Angular 7 项目,但遇到了一个我没想到的奇怪情况。 Angular 和 TypeScript 有点新。 我想在我的 html 中使用 4 个不同的 css 类之一。类名是根据 location.ts 文件中的计算确定的。不是什么复杂的事情,但仍然令人沮丧,为什么我不能以我认为可以的方式使用 angular/typescript。这样做的正确方法是什么?
location.ts 它是我尝试从我的 html 访问的 getcolor() 函数。
export class Location {
location: string;
name: string;
current: number;
max: number;
isActive: boolean = false;
color: string;
getcolor() {
let fraction = this.current / this.max;
switch (true) {
case (fraction < 0.25): { return "empty"; }
case (fraction < 0.5): { return "half-empty"; }
case (fraction < 0.75): { return "half-full"; }
case (fraction < 1): { return "full"; }
default: { return ""; }
}
}
}
location.service.ts
getLocationList(): Observable<Location[]> {
let list = this.http.get<Location[]>(this.url + "locations/");
return list;
};
map.component.ts
constructor(private locationService: LocationService) { }
public locationList: Location[];
ngOnInit() {
this.locationService.getLocationList().subscribe(e => this.locationList = e);
}
map.component.html 每张卡片都应该有四种不同的 CSS 样式之一。可能不是这样做的方法,但现在我们只需要一些工作。任何对更正确方法的建议表示赞赏:) 我只是尝试调用 Location 类上的方法来获取要使用的 css 样式的名称。
<div *ngFor="let loc of locationList" class="card {{loc.getcolor()}}">
<span><strong>{{loc.location}}</strong> - {{loc.name}}</span>
<div>
Storage: {{loc.current}}/{{loc.max}} tons
</div>
<div>
Remaining: {{loc.max - loc.current}} tons
</div>
</div>
【问题讨论】:
-
请显示
/locations端点的结果是什么样的。还有localionList的初始值是多少? -
从 map.component.ts 添加了更多代码。希望这会有所帮助。
标签: angular typescript angular7