当动态对象已经具有ngClass条件时,将多个类添加到动态对象Angular(4)

时间:2017-06-21 16:53:36

标签: angular typescript ng-class ngfor

我在定义特定类做动态元素时遇到了一些麻烦,看看这个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"]
        }]
    }
}

每个按钮都有选中的类,具体取决于用户是否选择了该类:

<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>

有什么办法可以吗?添加一个类数组(如果存在),并根据 filterData [item.id] 添加'selected'类  (布尔值)

1 个答案:

答案 0 :(得分:1)

您可以使用类绑定:

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

和你的ngClass列表:

[ngClass]="item[classes]"