我收到以下错误: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>
答案 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>
答案 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
希望有帮助,欢呼!