Search code examples
angulartypescriptng-classngfor

Add multiple classes to dynamic objects when it has already an ngClass condition Angular (4)


I'm having some trouble to define specific classes do dynamic elements, take a look at this JSON:

filterData = {
    "highlights": {
        "title": "Destaques",
        "options": [{
            "id": 1,
            "title": "Outlet",
            "alias": "outlet",
            "counter": 3,
            "classes": ["outlet", "feb", "jun"]
        }, {
            "id": 2,
            "title": "Novidades",
            "alias": "news",
            "counter": 0,
            "classes": ["news", "may"]
        }, {
            "id": 3,
            "title": "Promoção",
            "alias": "promo",
            "counter": 1,
            "classes": ["promo"]
        }]
    }
}

Each button has its selected class, depending if it's selected or not by the user:

<div
    *ngIf="filterEnabled"
    class="filters_btns"
>
    <button 
        *ngFor="let item of filtersList.options" 
        type="button" 
        class="btn"
        (click)="toggleFilterOption(item)"
        [ngClass]="{ 'selected': filterData[item.id]" <-- also add all of the classes of this array (item.classes) if some exists
    >{{ item.title }}</button>

</div>

There is any way to do this? Add an array of classes (if them exist), and also add the 'selected' class according to the filterData[item.id] (boolean)


Solution

  • You can use the class binding for that:

    [class.selected]="filterData[item.id]" 
    

    and the ngClass for you list:

    [ngClass]="item[classes]"