Я работаю над проектом Angular 7 и столкнулся со странной ситуацией, которую я не ожидал. Немного нового в Angular и TypeScript.
Я хочу использовать один из 4 различных классов CSS в моем HTML. Имя класса определяется на основе расчета в файле location.ts. Не что-то сложное, но все же расстраивает, почему я не могу использовать angular / typcript так, как я думал. Как правильно сделать что-то подобное?
location.ts
Это функция getcolor (), которую я пытаюсь найти из моего HTML.
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>