angularseparation-of-concerns

Where to write UI logic in an Angular app?


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.

<div *ngIf="car.type == carType.HATCHBACK" class="hatchback-icon-class"> ... </div>
<div *ngIf="car.type == carType.COUPE" class="coupe-icon-class"> ... </div>
...

Solution

  • 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