Assume I have an Angular app with two views. The first view shows a preview of some object, let's say a car, and the other view shows detailed information of that car. The car model would be something similar to:
export class Car {
model: string;
type: CarTypeEnum;
...;
}
Let's say I want both views to show me an Icon representing the car's type. The logic would be:
switch(someCar.type) {
case CarTypeEnum.HATCHBACK: return icons.hotHatch;
case CarTypeEnum.SEDAN: return icons.sedan;
case CarTypeEnum.SUV: return icons.suv;
case CarTypeEnum.COUPE: return icons.coupe;
case CarTypeEnum.VAN: return icons.van;
case CarTypeEnum.WAGON: return icons.wagon;
}
Where should this logic for getting the icon based on the car type go?
- Should I create a property in the car model class?
export class Car {
model: string;
type: CarTypeEnum;
...;
get typeIcon() {
// switch goes here
}
}
This feels somewhat right, given that I'm using this in two separate views, but it also feels like I'm polluting the model.
Should I add this code to a method and duplicate it into the two views component class? What if I had to use this code in 10 views, would I duplicate this logic 10 times in each of their respective component?
Should I create some static helper class containing a method with this logic, taking a car as a parameter, which I would then call in each component class?
Should I add the logic straight into the view?
<div *ngIf="car.type == carType.HATCHBACK" class="hatchback-icon-class"> ... </div>
<div *ngIf="car.type == carType.COUPE" class="coupe-icon-class"> ... </div>
...
- Should I generate an Angular component that would take the car type as an input? This would be reusable but kind of overkill just to render this icon, no?