Home >>Angular7 Tutorial >Angular7 Materials/CDK-Drag and Drop
Added to Angular 7 CDK, the new drag and drop feature helps to drag and drop the elements from the list. Using an example, we'll understand the workings of Drag and Drop Module. In cdk is added the feature. We need to download the dependency first as shown below –
npm install @angular/cdk --save
When that step is completed. Let's import to app.module.ts the drag and drop module as shown below –
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule , RoutingComponent} from './app-routing.module';
import { AppComponent } from './app.component';
import { NewCmpComponent } from './new-cmp/new-cmp.component';
import { ChangeTextDirective } from './change-text.directive';
import { SqrtPipe } from './app.sqrt';
import { MyserviceService } from './myservice.service';
import { HttpClientModule } from '@angular/common/http';
import { ScrollDispatchModule } from '@angular/cdk/scrolling';
import { DragDropModule } from '@angular/cdk/drag-drop';
@NgModule({
declarations: [
SqrtPipe,
AppComponent,
NewCmpComponent,
ChangeTextDirective,
RoutingComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
ScrollDispatchModule,
DragDropModule
],
providers: [MyserviceService],
bootstrap: [AppComponent]
})
export class AppModule { }
As seen above, the DragDropModule is imported from '@angular/cdk/drag-drop' and the module is added to the import list.
We must use information to be shown on the screen from the api (http:/jsonplaceholder.typicode.com/users). We have a service that will get the api data as shown below –
myservice.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class MyserviceService {
private finaldata = [];
private apiurl = "http://jsonplaceholder.typicode.com/users";
constructor(private http: HttpClient) { }
getData() {
return this.http.get(this.apiurl);
}
}
Once done call the service inside app.component.ts as shown below −
import { Component } from '@angular/core';
import { MyserviceService } from './myservice.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 7 Project!';
public personaldetails = [];
constructor(private myservice: MyserviceService) {}
ngOnInit() {
this.myservice.getData().subscribe((data) => {
this.personaldetails = Array.from(Object.keys(data), k=>data[k]);
console.log(this.personaldetails);
});
}
}
In personal details variable we have the required data available. Now let's use the same to show the user the way below –
<h3>Example 1 Drag and Drop Module Angular 7 </h3>
<div>
<div *ngFor="let item of personaldetails; let i = index" class="divlayout”>
{{item.name}}
</div >
</div>
We added class = "divlayout," and the class details are in app.component.css.
.divlayout{ width: 40%; background-color: #ccc; margin-bottom: 5px; padding: 10px 10px; border: 3px solid #73AD21; }
It won't drag and drop anything, in app.component.html we need to add the dragdrop cdk properties as shown below.
<h3>Example of Drag and Drop Module in Angular 7</h3>
<div cdkDropList
#personList = "cdkDropList"
[cdkDropListData] = "personaldetails"
[cdkDropListConnectedTo] = "[userlist]"
class = "example-list"
(cdkDropListDropped) = "onDrop($event)" >
<div *ngFor = "let item of personaldetails;
let i = index" class = "divlayout" cdkDrag>
{{item.name}}
</div >
</div>
The highlighted ones are all the properties required for drag-and - drop. This helps you to drag the element while searching in the browser. It won't drop it in the list, and will remain as it is when you leave your mouse pointer.
Here it helps you to move the element from the list, but it will go and settle in the same position until you remove the mouse pointer. To add the drop feature, the event onDrop must be added to app.component.ts as shown below −
We need to import the dragdrap cdk modules first as shown below –
import {CdkDragDrop, moveItemInArray, transferArrayItem} from '@angular/cdk/drag-drop';
Here is the full code in app.component.ts −
import { Component } from '@angular/core';
import { MyserviceService } from './myservice.service';
import {CdkDragDrop, moveItemInArray, transferArrayItem} from '@angular/cdk/drag-drop';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 7 Project!';
public personaldetails = [];
constructor(private myservice: MyserviceService) {}
ngOnInit() {
this.myservice.getData().subscribe((data) => {
this.personaldetails = Array.from(Object.keys(data),
k=>data[k]);
console.log(this.personaldetails);
});
}
onDrop(event: CdkDragDrop<string[]>) {
if (event.previousContainer === event.container) {
moveItemInArray(event.container.data,
event.previousIndex, event.currentIndex);
} else {
transferArrayItem(event.previousContainer.data,
event.container.data,
event.previousIndex,
event.currentIndex);
}
}
}
The onDrop feature makes sure that the element dragged in the correct position is lowered.
It makes use of the movingItemInArray and transferArrayItem that we imported from the module cdk dragdrop.