0

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)

1 Answer 1

1

You can use the class binding for that:

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

and the ngClass for you list:

[ngClass]="item[classes]"
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Meir, it works perfectly! Just one small correction, the classes is an property of item, so it will be like: item.classes or item['classes']
You're right. I focused on the syntax, not the specifics 😀

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.