将新项目添加到数组时刷新 sortable

Refresh sortable when a new item is added to the array

可排序组件仅显示初始数组元素。当一个新值被推入数组时,sortable 不显示它。

组件: 从“@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");
  }
}

模板:

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

解决方法:手动调用 SortableComponent 的 writeValue

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);
  }
}

应添加import { SortableComponent } from 'ngx-bootstrap';

它将起作用。

传播运算符在这个问题上对我来说效果很好:

addItem(){ this.itemStringsLeft = [...this.itemStringsLeft, {name: 'Windstorm', range: 5}]; }

重新分配列表值的另一种解决方法:

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