angularangular-ngselect

Angular ng-select: GroupBy array ng-select


Hi i have a problem with my ng-select, in this case storeTypes is an array, if storeTypeswould be an string there functionality has been perfect, but I nees that this variable are an string[]. What can I do?

@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() {
    }
    
}

Raw now i see that: enter image description here

I need this: enter image description here


Solution

  • One problem is groupby should be [groupby]. Secondly, you should create a helper function to group as groupby will either take property name or a function.

    Try below:

    @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() {
        }
        
    }