Search code examples
angulartypescriptngx-bootstrap

Use ngx-bootstrap Sortable with template


I would like to use the Sortable component of the ngx-bootstrap library. The problem is that using a template the sortable items are empty. My items are objects with some simple values including name and id. I'd like to show the name property value. These are my ugly bs-sortable and ng-template tags:

<bs-sortable
    [(ngModel)]="items"
    [itemTemplate]="itemTemplate"
    itemClass="list-group-item"                    
    itemActiveClass="sortable-item-active"
    placeholderItem=""
    placeholderClass="placeholderStyle"
    wrapperClass="sortable-wrapper"></bs-sortable>
<ng-template #itemTemplate let-item="item" let-index="index">
                <span (click)="selectItem(item)" [class.active]="item.id === currentItem.id" [class.iteminactive]="!item.active">
                    {{item.name}}
                </span>
            </ng-template>

In my component.ts I have an items:IssuePriority[] property that contains two values. This code is producing two empty rows that are sortable just both of them are empty. What am I doing wrong? It works without using a template but I need to use at least this template to be able to set my css classes and methods.


Solution

  • Sortable is an experimental component, so there may be some gaps in the documentation. In your case, when you have an array of objects in ngModel, item variable in ng-template is a wrapper around your object. To get access to your object, use item.value.xxx instead of item.xxx.

    <ng-template #tpl let-item="item"><span>{{item.value.name}}</span></ng-template>

    Example - https://stackblitz.com/edit/angular-hlawza-sn8hdh?file=app/custom-item-template.html