ng2-bootstrap

Refresh sortable when a new item is added to the array


Sortable component only shows initial array elements. When a new value is pushed into array, the sortable does not display it.

Component: import { Component } from '@angular/core';

@Component({
  selector: 'custom-item-template-demo',
  templateUrl: './custom-item-template.html'
})
export class CustomItemTemplateDemoComponent {
  public itemStringsLeft: any[] = [
    'Windstorm',
    'Bombasto',
    'Magneta',
    'Tornado'
  ];

  public addItem() {
    this.itemStringsLeft.push("new item");
  }
}

Template:

<button type="button" (click)="addItem()">Add</button> 
<template #itemTemplate let-item="item" let-index="index"><span>{{index}}: {{item.value}}</span></template>
  {{itemStringsLeft.length}}
  <pre>{{ itemStringsLeft | json }}</pre>
  <bs-sortable
    [(ngModel)]="itemStringsLeft"
    [itemTemplate]="itemTemplate"
    itemClass="sortable-item"
    itemActiveClass="sortable-item-active"
    placeholderItem="Drag here"
    placeholderClass="placeholderStyle"
    wrapperClass="sortable-wrapper"
  ></bs-sortable>

Solution

  • Workaround: Call manually to writeValue of the SortableComponent

    import { Component, ViewChild } from '@angular/core';
    
    @Component({
      selector: 'custom-item-template-demo',
      templateUrl: './custom-item-template.html'
    })
    export class CustomItemTemplateDemoComponent {
      public itemStringsLeft: any[] = [
        'Windstorm',
        'Bombasto',
        'Magneta',
        'Tornado'
      ];
    
    @ViewChild(SortableComponent, {static: false}) sortableComponent: SortableComponent;
      public addItem() {
        this.itemStringsLeft.push("new item");
        this.sortableComponent.writeValue(this.itemStringsLeft);
      }
    }