Search code examples
javascriptangulartypescriptng-class

Angular - How can I move ngClass logic from template to ts file?


In Angular application I am using dropdown filters for user selection. I have add logic in ngClass

<div [ngClass]="i > 2 && 'array-design'">

How can I move the logic for classed to the controller? As when they are in the template it not possible to unit test them.

<ng-container *ngIf="searchFilters.length > 0; else loading">
        <div class="filter-items" *ngFor="let filter of searchFilters; index as i">
            <div [ngClass]="i > 2 && 'array-design'">
                <app-multi-select [items]="filter.navigators" [title]="filter.name"></app-multi-select>
            </div>
        </div>
    </ng-container>

.scss

  .cross-reactivity, .array-design{
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-right: 5px;
  }

Solution

  • You can move the conditional statement into a function and use its return in HTML.


    html

    [ngClass]="filterClass(i)"
    

    ts

    const filterClass = (i) => i > 2 && 'array-design';