Issue
I am working on an angular app. I am using drag and drop in my application for reordering list. Code is as follows:
https://stackblitz.com/edit/angular-drag-drop-sortable?file=app%2Fcdk-drag-drop-sorting-example.html
component:
import {Component} from '@angular/core';
import {CdkDragDrop, moveItemInArray} from '@angular/cdk/drag-drop';
/**
* @title Drag&Drop sorting
*/
@Component({
selector: 'cdk-drag-drop-sorting-example',
templateUrl: 'cdk-drag-drop-sorting-example.html',
styleUrls: ['cdk-drag-drop-sorting-example.css'],
})
export class CdkDragDropSortingExample {
movies = [
'Episode I - The Phantom Menace',
'Episode II - Attack of the Clones',
'Episode III - Revenge of the Sith',
'Episode IV - A New Hope',
'Episode V - The Empire Strikes Back',
'Episode VI - Return of the Jedi',
'Episode VII - The Force Awakens',
'Episode VIII - The Last Jedi'
];
drop(event: CdkDragDrop<string[]>) {
moveItemInArray(this.movies, event.previousIndex, event.currentIndex);
}
}
html:
<div cdkDropList class="example-list" (cdkDropListDropped)="drop($event)">
<div class="example-box" *ngFor="let movie of movies" cdkDrag>{{movie}}</div>
</div>
CSS:
.example-list {
width: 500px;
max-width: 100%;
border: solid 1px #ccc;
min-height: 60px;
display: block;
background: white;
border-radius: 4px;
overflow: hidden;
}
.example-box {
padding: 20px 10px;
border-bottom: solid 1px #ccc;
color: rgba(0, 0, 0, 0.87);
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
box-sizing: border-box;
cursor: move;
background: white;
font-size: 14px;
}
.cdk-drag-preview {
box-sizing: border-box;
border-radius: 4px;
box-shadow: 0 5px 5px -3px rgba(0, 0, 0, 0.2),
0 8px 10px 1px rgba(0, 0, 0, 0.14),
0 3px 14px 2px rgba(0, 0, 0, 0.12);
}
.cdk-drag-placeholder {
opacity: 0;
}
.cdk-drag-animating {
transition: transform 250ms cubic-bezier(0, 0, 0.2, 1);
}
.example-box:last-child {
border: none;
}
.example-list.cdk-drop-list-dragging .example-box:not(.cdk-drag-placeholder) {
transition: transform 250ms cubic-bezier(0, 0, 0.2, 1);
}
I want that whenever I drag and drop a item, I want to have it's name in a variable. Like if I drag and drop 'Episode I - The Phantom Menace' then I want to store 'Episode I - The Phantom Menace' in a variable. I have currentIndex in event.currentIndex but how can I get the name?
Solution
You can get the name with the help of currentIndex. You have currentIndex just pass the current index in your movies array.
this.movies[event.currentIndex]
First create a variable
name: string = "";
In your drop function add the following line
this.name = this.movies[event.currentIndex]
Now the name will be stored in name variable. Like if you drag and drop 'Episode I - The Phantom Menace' then 'Episode I - The Phantom Menace' will store in a name variable.
Answered By - Faiz Shahid
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.