将新项添加到数组

时间:2017-03-07 10:46:01

标签: ng2-bootstrap

可排序组件仅显示初始数组元素。将新值推入数组时,sortable不会显示它。

组件:     从' @ angular / core';

导入{Component}
@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>

4 个答案:

答案 0 :(得分:2)

解决方法:手动调用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) sortableComponent: SortableComponent;
  public addItem() {
    this.itemStringsLeft.push("new item");
    this.sortableComponent.writeValue(this.itemStringsLeft);
  }
}

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

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

它将正常工作。

答案 3 :(得分:0)

传播操作员在此问题上对我来说效果很好:

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