我正在尝试组合 this example (创建所选值的 mat-chips 的下拉选择),具有借用自 Angular Material 的 Mat-Chip examples 的拖放功能。 (从顶部开始的第二个示例)但由于某种原因,拖放不起作用。我可以拖动一个芯片,当将其悬停在另一个芯片上时,它似乎会改变索引,但是当我放下它(释放鼠标按钮)时,它会返回到原来的位置。这是 Material 组件的兼容性问题吗?这是我当前的代码:
HTML:
<mat-form-field class="field">
<mat-label>Choose values</mat-label>
<mat-select [formControl]="toppingsControl" multiple>
<mat-select-trigger>
<mat-chip-list
cdkDropList
cdkDropListOrientation="horizontal"
(cdkDropListDropped)="drop($event)"
>
<mat-chip
cdkDrag
*ngFor="let topping of toppingsControl.value"
[removable]="true"
(removed)="onToppingRemoved(topping)"
>
{{ topping.name }}
<mat-icon matChipRemove>cancel</mat-icon>
</mat-chip>
</mat-chip-list>
</mat-select-trigger>
<mat-option *ngFor="let topping of toppings" [value]="topping">{{
topping.name
}}</mat-option>
</mat-select>
</mat-form-field>
typescript :
import { Component } from "@angular/core";
import {FormControl} from '@angular/forms';
import { CdkDragDrop, moveItemInArray } from "@angular/cdk/drag-drop";
export interface Topping {
name: string;
}
@Component({
selector: 'app-control',
templateUrl: 'control.component.html',
styleUrls: ['control.component.scss'],
})
export class ControlComponent {
toppingsControl = new FormControl([]);
toppings: Topping[] = [
{name: 'Value_0'},
{name: 'Value_1'},
{name: 'Value_2'},
{name: 'Value_3'},
{name: 'Value_4'}
];
onToppingRemoved(topping: string) {
const toppings = this.toppingsControl.value as string[];
this.removeFirst(toppings, topping);
this.toppingsControl.setValue(toppings); // To trigger change detection
}
private removeFirst<T>(array: T[], toRemove: T): void {
const index = array.indexOf(toRemove);
if (index !== -1) {
array.splice(index, 1);
}
}
drop(event: CdkDragDrop<Topping[]>) {
moveItemInArray(this.toppings, event.previousIndex, event.currentIndex);
}}
最佳答案
我复制了你的例子,发现一个错误
错误1:当您拖动(此处为drop
函数)时,Chips仅会更改数组参数,但不会更改formcontroller参数。如果您更改 Controller 的位置,那么您将获得所需的内容。即,
drop(event: CdkDragDrop<Topping[]>) {
moveItemInArray(this.toppings, event.previousIndex, event.currentIndex);
}}
变成了
drop(event: CdkDragDrop<Topping[]>) {
moveItemInArray(this.toppings, event.previousIndex, event.currentIndex);
moveItemInArray(this.toppingsControl.value, event.previousIndex, event.currentIndex);
}
希望这能消除您的疑虑。如需进一步引用,请参阅以下示例的多重测试
。在这里您可以与原始示例(您提供的)进行比较。
关于angular - 添加拖放至 mat-form-field 内的 mat-chip 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69371050/