【发布时间】:2021-11-21 01:06:03
【问题描述】:
我正在尝试将this example(创建所选值的垫片的下拉选择)与从 Angular Material 的Mat-Chip examples(顶部的第二个示例)借用的拖放功能结合起来,但由于某种原因,拖动并且 drop 不起作用。我可以拖动一个芯片,当它悬停在另一个芯片上时,它似乎会改变索引,但是当我放下它(释放鼠标按钮)时,它会回到原来的位置。这是材质组件的兼容性问题吗?这是我目前的代码:
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>
打字稿:
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);
}}
【问题讨论】: