角度ng-select:GroupBy数组ng-select

时间:2020-09-21 16:37:41

标签: angular angular-ngselect

嗨,我的ng-select出现了问题,在这种情况下,storeTypes是一个数组,如果storeTypes将是一个字符串,那么功能已经很完善了,但是我需要这个变量是string []。我该怎么办?

@Component({
    selector: 'my-app',
    template: `
             
        <label>Grouping</label>
        <ng-select [items]="accounts"
                bindLabel="label"
                bindValue="code"
                groupBy="storeTypes[0]"
                [(ngModel)]="selectedAccount">
        </ng-select>
        `
})
export class AppComponent {

    selectedAccount = '9'
    accounts = [
        {code: "9", checked: false, label: "Adidas", storeTypes:["Store"]},
        {code: "91", checked: false, label: "Nike", storeTypes:["Store"]},
        {code: "92", checked: false, label: "5guys", storeTypes:["Restaurant"]},
        {code: "93", checked: false, label: "McDonal", storeTypes:["Restaurant"]},
        {code: "94", checked: false, label: "FastFood", storeTypes:["Restaurant"]}
   ];
   
    constructor() {
    }
    
}

现在我看到了: enter image description here

我需要这个: enter image description here

1 个答案:

答案 0 :(得分:0)

一个问题是 groupby 应该是 [groupby] 。 其次,您应该创建一个助手函数进行分组,因为groupby将采用属性名称或函数。

尝试以下方法:

@Component({
    selector: 'my-app',
    template: `
             
        <label>Grouping</label>
        <ng-select [items]="accounts"
                bindLabel="label"
                bindValue="code"
                [groupBy]="groupingHelper"
                [(ngModel)]="selectedAccount">
        </ng-select>
        `
})
export class AppComponent {

    groupingHelper(item){return item.storeTypes[0]}
    selectedAccount = '9'
    accounts = [
        {code: "9", checked: false, label: "Adidas", storeTypes:["Store"]},
        {code: "91", checked: false, label: "Nike", storeTypes:["Store"]},
        {code: "92", checked: false, label: "5guys", storeTypes:["Restaurant"]},
        {code: "93", checked: false, label: "McDonal", storeTypes:["Restaurant"]},
        {code: "94", checked: false, label: "FastFood", storeTypes:["Restaurant"]}
   ];
   
    constructor() {
    }
    
}