How to change order of a drag and drop list in Angular Material with up or down buttons? So I want to move an item up or down.
template.html
<div cdkDropList class="dlist" (cdkDropListDropped)="drop($event)">
<div class="category" cdkDrag *ngFor="let category of categories">
<div class="orderer">
<button class="up">Up</button>
<button class="down">Down</button>
</div>
</div>
</div>
component.ts
public drop(event: CdkDragDrop<string[]>) {
moveItemInArray(this.categories, event.previousIndex, event.currentIndex);
}
You can call a standard function binded to event click of button like this:
component.ts
order(index:number,up: boolean) {
if(up) // move up
{
if(index === 0) {
console.log('do nothing')
}
else{
const temp = this.movies[index-1];
this.movies[index-1]=this.movies[index];
this.movies[index]=temp;
}
}
else{
if(index == this.movies.length) {
console.log('do nothing')
}
else {
const temp = this.movies[index+1];
this.movies[index+1]=this.movies[index];
this.movies[index]=temp;
}
}
}
component.html
<span style="padding:20px"></span>
<hr>
<div cdkDropList class="example-list" (cdkDropListDropped)="drop($event)">
<div class="example-box" *ngFor="let movie of movies; let i = index" cdkDrag>{{movie}}
<div><button mat-fab (click)="order(i,true)">Up</button>
<button mat-fab (click)="order(i,false)">Down</button></div>
</div>
</div>
example here .
There is a solution If you want to swap in-place without temp variable:
function moveItemInArray(categories, previousIndex, currentIndex){ categories = categories || [1,2,3,4,5,6]; // you wont here in your solution previousIndex = previousIndex || 1; // you wont here in your solution currentIndex = currentIndex || 2; // you wont here in your solution console.log(categories.toString()); categories[currentIndex] = categories[previousIndex] + (categories[previousIndex] = categories[currentIndex]) - categories[currentIndex]; console.log(categories.toString()); }
<body onload="moveItemInArray()"></body>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.