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?
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>
...
If you are going to use that icon all along the app, I would recommend creating a component with an input binding (as you say in your last paragraph).
Angular really encourages you to make presentational components that are easy to test and reuse, following KISS and SOLID principles.
More info in this article: https://indepth.dev/posts/1066/presentational-components-with-angular