带有动态列表的数组之间的Angular7 cdkDropList

时间:2018-11-07 13:38:52

标签: angular angular-material

我收到以下错误:ERROR TypeError: Cannot assign to read only property '2' of string 'One' 从以下数据列表中创建,该数据列表是我模仿实际数据的外观而创建的,以及我从角材料文档中看到的用于此类动态列表的模板视图。但是,即使他们说了该怎么办,也没有给出一个例子。

我无法执行以下操作:

组件:

lists = [];

ngOnInit() {
    this.lists = [{number: 'One', amount: [1, 2, 3, 4]}, {number: 'Two', amount: [5, 6, 7, 8]}, {number: 'Three', amount: [9, 10, 11, 12]}];
}

drop(event: CdkDragDrop<string[]>) {
    if (event.previousContainer === event.container) {
        moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
    } else {
        transferArrayItem(event.previousContainer.data,
            event.container.data,
            event.previousIndex,
            event.currentIndex);
    }
}

模板:

<div cdkDropList [cdkDropListData]="list.number" *ngFor="let list of lists" (cdkDropListDropped)="drop($event)">
    {{list.number}}
    <div cdkDrag [cdkDragData]="item" *ngFor="let item of list.amount">
        {{item}}
    </div>
</div>

2 个答案:

答案 0 :(得分:2)

您应该获得列表项的实际索引。 试试这个:

TS:

activeNumIndex: number;
enter(i) {
    this.activeNumIndex = i;
  }

  drop(event: CdkDragDrop<string[]>) {
    if (event.previousContainer === event.container) {
      moveItemInArray(this.lists[this.activeNumIndex].amount, event.previousIndex, event.currentIndex);
    } else {
      transferArrayItem(event.previousContainer.data,
        event.container.data,
        event.previousIndex,
        event.currentIndex);
    }
  }

HTML:

<div cdkDropList [cdkDropListData]="list.number" *ngFor="let list of lists; let i=index;" (cdkDropListDropped)="drop($event)">
    {{list.number}}
    <div cdkDrag [cdkDragData]="item" *ngFor="let item of list.amount" (mouseenter)="enter(i)" style="border:1px solid black">
        {{item}}
    </div>
</div>

Here's a duplicate in Stackblitz

答案 1 :(得分:0)

如果要在数组之间移动项目,可以使用cdkDropList标记每个#mark-name并使用cdkDropListConnectedTo指令连接它们。

如果cdkDropList的数目未知,则可以使用cdkDropListGroup伪指令自动建立cdkDropList之间的连接。

示例为:

<div cdkDropListGroup>
    <div cdkDropList *ngFor="let list of lists; let i=index;"
         [cdkDropListData]="list.number" 
         (cdkDropListDropped)="drop($event)">{{list.number}}

           <div cdkDrag *ngFor="let item of list.amount"
                [cdkDragData]="item"  
                (mouseenter)="enter(i)" 
                style="border:1px solid black">{{item}}
           </div>
    </div>
</div>

Stackblitz示例

下面是一些示例code copied from angular material example

并带有dynamic number of list

希望有帮助,欢呼!