在处理拖放操作时,需要手动从数组中删除项目并重新排序。以下是示例代码:
// HTML模板
// 组件 export class MyComponent implements OnInit { items: FormArray;
constructor(private fb: FormBuilder) {}
ngOnInit() { this.items = this.fb.array([ { name: 'Item 1' }, { name: 'Item 2' }, { name: 'Item 3' }, { name: 'Item 4' }, ]); }
onDrop(event: CdkDragDrop
// 帮助函数 export function moveItemInFormArray(array: FormArray, fromIndex: number, toIndex: number) { const item = array.at(fromIndex); array.removeAt(fromIndex); array.insert(toIndex, item); }
export function transferItemInFormArray(fromArray: FormArray, fromIndex: number, toIndex: number) { const item = fromArray.at(fromIndex); fromArray.removeAt(fromIndex);
const toArray = toIndex >= fromArray.length ? fromArray : fromArray.parent.get('items') as FormArray; toArray.insert(toIndex, item); }