New Angular Drag And Drop Feature - ngDragDrop

Here in this post, I am going to explain a bit about one of the Angular 7 feature, which is Drag and Drops. At the end of this article, you will have an application which fetches the real data from the database and binds it to the UI and then performs multi-directional drag and drops

Introduction

As you all know Angular 7 is out with some cool new features. I really appreciate that you want to experience the brand new Angular. Here, in this post, I am going to explain a bit about one of the Angular 7 features, which is "Drag and Drop". At the end of this article, you will have an application which fetches the real data from the database and binds it to the UI and then performs multi-directional drag and drop. Enough talking, let’s jump into the setup. I hope you will find this post useful. You can always read this article in my blog here

Source Code

The source code can be found here.

Background

As Angular 7 was out last week, I wanted to try a few things with the same and that is the cause for this article. If you are really new to Angular, and if you need to try some other things, visiting my articles on the same topic wouldn’t be a bad idea.

Creating ngDragDrop app

The first thing we are going to do is to create a dummy application.

Installing Angular CLI

Yes, as you guessed, we are using Angular CLI. If you haven’t installed Angular CLI, I recommend you to install the same. It is a great CLI tool for Angular; I am sure you will love that. You can do that by running the below command.

npm install -g @angular/cli

Once we set up this project, we will be using the Angular CLI commands. You can visit here for understanding the things you can do with Angular CLI.

Generating a new project

Now, it is time to generate our new project. We can use the below command for the same.

ng new ngDragDrop

And you will be able to see all the hard work this CLI is doing for us. Now that we have created our application, let’s run it and see if it is working or not.

  1. ng serve --open (if you need to open the browser by the app)
  2. ng serve (if you want to manually open the browser).
  3. You can always use 'ng s' as well

The command will build your application and run it in the browser.

As we develop the app, we will be using Angular Material for the designing part and we can install it now itself along with the animation and cdk. With Angular 6+ versions, you can also do this by following the below command.

ng add @angular/material
 
Generate and set up header component

Now, we have an application to work with. Let’s create a header component now.

ng g c header

The above command will generate all the files you need to work with and it will also add this component to the app.module.ts. I am going to edit only the HTML of the header component for myself and not going to add any logic. You can add anything you wish.

  1. <div style="text-align:center">  
  2.    <h1>  
  3.       Welcome to ngDragDropg at <a href="https://sibeeshpassion.com">Sibeesh Passion</a>  
  4.    </h1>  
  5. </div>  
Set up footer component

Create the footer component by running the below command.

ng g c footer

And you can edit or style them as you wish.

  1. <p>  
  2.    Copyright @SibeeshPassion 2018 - 2019 🙂  
  3. </p>  
Set up app-routing.module.ts

We are going to create a route only for home.

  1. import {  
  2.     NgModule  
  3. } from '@angular/core';  
  4. import {  
  5.     Routes,  
  6.     RouterModule  
  7. } from '@angular/router';  
  8. import {  
  9.     HomeComponent  
  10. } from './home/home.component';  
  11. const routes: Routes = [{  
  12.     path: '',  
  13.     redirectTo: '/home',  
  14.     pathMatch: 'full'  
  15. }, {  
  16.     path: 'home',  
  17.     component: HomeComponent  
  18. }];  
  19. @NgModule({  
  20.     imports: [RouterModule.forRoot(routes)],  
  21.     exports: [RouterModule]  
  22. })  
  23. export class AppRoutingModule {}  
Set up router outlet in app.component.html

Now, we have a route and it is time to set up the outlet.

  1. <app-header></app-header>  
  2. <router-outlet>  
  3. </router-outlet>  
  4. <app-footer></app-footer>  
Set up app.module.ts

Every Angular app will be having at least one NgModule class, AppModule, that resides in app.module.ts. You can always learn about the Angular architecture here.

  1. import {  
  2.     BrowserModule  
  3. } from '@angular/platform-browser';  
  4. import {  
  5.     NgModule  
  6. } from '@angular/core';  
  7. import {  
  8.     MatButtonModule,  
  9.     MatCheckboxModule,  
  10.     MatMenuModule,  
  11.     MatCardModule,  
  12.     MatSelectModule  
  13. } from '@angular/material';  
  14. import {  
  15.     AppRoutingModule  
  16. } from './app-routing.module';  
  17. import {  
  18.     AppComponent  
  19. } from './app.component';  
  20. import {  
  21.     HeaderComponent  
  22. } from './header/header.component';  
  23. import {  
  24.     FooterComponent  
  25. } from './footer/footer.component';  
  26. import {  
  27.     HomeComponent  
  28. } from './home/home.component';  
  29. import {  
  30.     MovieComponent  
  31. } from './movie/movie.component';  
  32. import {  
  33.     MovieService  
  34. } from './movie.service';  
  35. import {  
  36.     HttpModule  
  37. } from '@angular/http';  
  38. import {  
  39.     BrowserAnimationsModule  
  40. } from '@angular/platform-browser/animations';  
  41. import {  
  42.     DragDropModule  
  43. } from '@angular/cdk/drag-drop';  
  44. @NgModule({  
  45.     declarations: [  
  46.         AppComponent,  
  47.         HeaderComponent,  
  48.         FooterComponent,  
  49.         HomeComponent,  
  50.         MovieComponent  
  51.     ],  
  52.     exports: [  
  53.         HttpModule,  
  54.         BrowserModule,  
  55.         AppRoutingModule,  
  56.         DragDropModule,  
  57.         MatButtonModule, MatCheckboxModule, MatMenuModule, MatCardModule, MatSelectModule, BrowserAnimationsModule  
  58.     ],  
  59.     imports: [  
  60.         HttpModule,  
  61.         BrowserModule,  
  62.         AppRoutingModule,  
  63.         DragDropModule,  
  64.         MatButtonModule, MatCheckboxModule, MatMenuModule, MatCardModule, MatSelectModule, BrowserAnimationsModule  
  65.     ],  
  66.     providers: [MovieService],  
  67.     bootstrap: [AppComponent]  
  68. })  
  69. export class AppModule {}  

Do you see a DragDropModule there? You should import it to use the drag and drop feature which resides in the @angular/cdk/drag-drop. As you might have already noticed, we have added one service called MovieService in the providers array. We will create one now.

Creating a movie service
  1. import {  
  2.     Injectable  
  3. } from '@angular/core';  
  4. import {  
  5.     RequestMethod,  
  6.     RequestOptions,  
  7.     Request,  
  8.     Http  
  9. } from '@angular/http';  
  10. import {  
  11.     config  
  12. } from './config';  
  13. @Injectable({  
  14.     providedIn: 'root'  
  15. })  
  16. export class MovieService {  
  17.     constructor(private http: Http) {}  
  18.     async get(url: string) {  
  19.         return await this.request(url, RequestMethod.Get);  
  20.     }  
  21.     async request(url: string, method: RequestMethod) {  
  22.         const requestOptions = new RequestOptions({  
  23.             method: method,  
  24.             url: `${config.api.baseUrl}${url}${config.api.apiKey}`  
  25.         });  
  26.         const request = new Request(requestOptions);  
  27.         return await this.http.request(request).toPromise();  
  28.     }  
  29. }  

I haven’t done much with the service class and didn’t implement the error mechanism and other things as I wanted to make this as short as possible. This service will fetch the movies from an online database TMDB and here in this article, I am using my own repository. I strongly recommend you to create your own instead of using the one mentioned here. Can we set up the config file now?

Set up config.ts

A configuration file is a way to arrange things  handily and you must implement in all the projects you are working with.

  1. const config = {  
  2.     api: {  
  3.         baseUrl: 'https://api.themoviedb.org/3/movie/',  
  4.         apiKey: '&api_key=c412c072676d278f83c9198a32613b0d',  
  5.         topRated: 'top_rated?language=en-US&page=1'  
  6.     }  
  7. };  
  8. export {  
  9.     config  
  10. };  
Creating a movie component

Let’s create a new component now to load the movie into it. Basically, we will be using this movie component inside the cdkDropList div. Our movie component will be having the HTML as below.

  1. <mat-card>  
  2.     <img mat-card-image src="https://image.tmdb.org/t/p/w185_and_h278_bestv2/{{movie?.poster_path}}">  
  3. </mat-card>  

I just made it as simple as is. But in the future, we can add a few more properties to the movie component and show them here. The TypeScript file will be having one property with @Input decorator so that we can input the values to it from the home component.

  1. import {  
  2.     Component,  
  3.     OnInit,  
  4.     Input  
  5. } from '@angular/core';  
  6. import {  
  7.     Movie  
  8. } from '../models/movie';  
  9. @Component({  
  10.     selector: 'app-movie',  
  11.     templateUrl: './movie.component.html',  
  12.     styleUrls: ['./movie.component.scss']  
  13. })  
  14. export class MovieComponent implements OnInit {  
  15.     @Input()  
  16.     movie: Movie;  
  17.     constructor() {}  
  18.     ngOnInit() {}  
  19. }  

Below is my model movie.

  1. export class Movie {  
  2.    poster_path: string;  
  3. }  

As I said, it has only one property; now, will add a few later.

Set up home component

Now, here is the main part - the place where we render our movies and perform drag and drop. I will be having a parent container as<div style="display: flex;"> so that the inner divs will be arranged horizontally. And I will be having two inner containers, one is to show all the movies and another one is to show the movies I am going to watch. I can just drag the movie from the left container to right and vice versa. Let’s design the HTML now. Below is all the movie collection.

  1. <div cdkDropList #allmovies="cdkDropList" [cdkDropListData]="movies" [cdkDropListConnectedTo]="[towatch]" (cdkDropListDropped)="drop($event)">  
  2.    <app-movie *ngFor="let movie of movies"[movie]="movie" cdkDrag></app-movie>  
  3. </div>  

As you can see, there are a few new properties I am assigning to both the app-movie and app-movie container.

  • cdkDropList is basically a container for the drag and drop items
  • #allmovies=”cdkDropList” is the id of our source container
  • [cdkDropListConnectedTo]=”[towatch]” is how we are connecting two app-movie containers, remember the “towatch” is the id of another cdkDropList container
  • [cdkDropListData]=”movies” is how we assign the source data to the list
  • (cdkDropListDropped)=”drop($event)” is the callback event whenever there is a drag and drop happening.
  • Inside the cdkDropList container, we are looping through the values and pass the movie to our own movie component which is app-movie
  • We should also add the property cdkDrag in our Draggable item, which is nothing but a movie.

Now, let us create another container which will be the collection of movies which I am going to watch.

  1. <div cdkDropList #towatch="cdkDropList" [cdkDropListData]="moviesToWatch" [cdkDropListConnectedTo]="[allmovies]" (cdkDropListDropped)="drop($event)">  
  2.    <app-movie *ngFor="let movie of moviesToWatch"[movie]="movie" cdkDrag></app-movie>  
  3. </div>  

As you can see, we are almost using the same properties as we did for the first container except for the id, cdkDropListData, and cdkDropListConnectedTo.

Finally, our home.component.html will be as given below.

  1. <div style="display: flex;">  
  2.     <div class="container">  
  3.         <div class="row">  
  4.             <h2 style="text-align: center">Movies</h2>  
  5.             <div cdkDropList #allmovies="cdkDropList" [cdkDropListData]="movies" [cdkDropListConnectedTo]="[towatch]" (cdkDropListDropped)="drop($event)">  
  6.                 <app-movie *ngFor="let movie of movies" [movie]="movie" cdkDrag></app-movie>  
  7.             </div>  
  8.         </div>  
  9.     </div>  
  10.     <div class="container">  
  11.         <div class="row">  
  12.             <h2 style="text-align: center">Movies to watch</h2>  
  13.             <div cdkDropList #towatch="cdkDropList" [cdkDropListData]="moviesToWatch" [cdkDropListConnectedTo]="[allmovies]" (cdkDropListDropped)="drop($event)">  
  14.                 <app-movie *ngFor="let movie of moviesToWatch" [movie]="movie" cdkDrag></app-movie>  
  15.             </div>  
  16.         </div>  
  17.     </div>  
  18. </div>  

Now, we need to get some data by calling our service. Let’s open our home.component.ts file.

  1. import {  
  2.     Component  
  3. } from '@angular/core';  
  4. import {  
  5.     MovieService  
  6. } from '../movie.service';  
  7. import {  
  8.     Movie  
  9. } from '../models/movie';  
  10. import {  
  11.     config  
  12. } from '../config';  
  13. import {  
  14.     CdkDragDrop,  
  15.     moveItemInArray,  
  16.     transferArrayItem  
  17. } from '@angular/cdk/drag-drop';  
  18. @Component({  
  19.     selector: 'app-home',  
  20.     templateUrl: './home.component.html',  
  21.     styleUrls: ['./home.component.scss']  
  22. })  
  23. export class HomeComponent {  
  24.     movies: Movie[];  
  25.     moviesToWatch: Movie[] = [{  
  26.         poster_path: 'https://cdn.sibeeshpassion.com/uC6TTUhPpQCmgldGyYveKRAu8JN.jpg'  
  27.     }];  
  28.     constructor(private movieService: MovieService) {  
  29.         this.getMovies();  
  30.     }  
  31.     private async getMovies() {  
  32.         const movies = await this.movieService.get(config.api.topRated);  
  33.         return this.formatDta(movies.json().results);  
  34.     }  
  35.     formatDta(_body: Movie[]): void {  
  36.         this.movies = _body.filter(movie => movie.poster_path !== 'https://cdn.sibeeshpassion.com/uC6TTUhPpQCmgldGyYveKRAu8JN.jpg');  
  37.     }  
  38.     drop(event: CdkDragDrop < string[] > ) {  
  39.         if (event.previousContainer === event.container) {  
  40.             moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);  
  41.         } else {  
  42.             transferArrayItem(event.previousContainer.data, event.container.data, event.previousIndex, event.currentIndex);  
  43.         }  
  44.     }  
  45. }  

Here, I am importing CdkDragDrop, moveItemInArray, transferArrayItem from ‘@angular/cdk/drag-drop’. This helps us to perform the drag and drop. In the constructor, we are fetching the data and assigning to the variable "movies" which is an array of the movie.

  1. private async getMovies(){  
  2.    const movies = await this.movieService.get(config.api.topRated);  
  3.    return this.formatDta(movies.json().results);  
  4. }  

I am setting the movies to watch collection as below, as I have already planned to watch that movie.

  1. moviesToWatch: Movie[] = [{  
  2.    poster_path: 'https://cdn.sibeeshpassion.com/uC6TTUhPpQCmgldGyYveKRAu8JN.jpg'  
  3. }];  

Remember, the drag and drop with two sources will not work if it doesn’t have at least one item in it. Because I set a movie in it, it doesn’t make any sense to show that movie in the other collection right?

  1. formatDta(_body: Movie[]): void {  
  2.     this.movies = _body.filter(movie => movie.poster_path !== 'https://cdn.sibeeshpassion.com/uC6TTUhPpQCmgldGyYveKRAu8JN.jpg');  
  3. }  

And below is our drop event.

  1. drop(event: CdkDragDrop < string[] > ) {  
  2.     if (event.previousContainer === event.container) {  
  3.         moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);  
  4.     } else {  
  5.         transferArrayItem(event.previousContainer.data, event.container.data, event.previousIndex, event.currentIndex);  
  6.     }  
  7. }  

The complete code for the home.component.ts will look like below.

  1. import {  
  2.     Component  
  3. } from '@angular/core';  
  4. import {  
  5.     MovieService  
  6. } from '../movie.service';  
  7. import {  
  8.     Movie  
  9. } from '../models/movie';  
  10. import {  
  11.     config  
  12. } from '../config';  
  13. import {  
  14.     CdkDragDrop,  
  15.     moveItemInArray,  
  16.     transferArrayItem  
  17. } from '@angular/cdk/drag-drop';  
  18. @Component({  
  19.     selector: 'app-home',  
  20.     templateUrl: './home.component.html',  
  21.     styleUrls: ['./home.component.scss']  
  22. })  
  23. export class HomeComponent {  
  24.     movies: Movie[];  
  25.     moviesToWatch: Movie[] = [{  
  26.         poster_path: 'https://cdn.sibeeshpassion.com/uC6TTUhPpQCmgldGyYveKRAu8JN.jpg'  
  27.     }];  
  28.     constructor(private movieService: MovieService) {  
  29.         this.getMovies();  
  30.     }  
  31.     private async getMovies() {  
  32.         const movies = await this.movieService.get(config.api.topRated);  
  33.         return this.formatDta(movies.json().results);  
  34.     }  
  35.     formatDta(_body: Movie[]): void {  
  36.         this.movies = _body.filter(movie => movie.poster_path !== 'https://cdn.sibeeshpassion.com/uC6TTUhPpQCmgldGyYveKRAu8JN.jpg');  
  37.     }  
  38.     drop(event: CdkDragDrop < string[] > ) {  
  39.         if (event.previousContainer === event.container) {  
  40.             moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);  
  41.         } else {  
  42.             transferArrayItem(event.previousContainer.data, event.container.data, event.previousIndex, event.currentIndex);  
  43.         }  
  44.     }  
  45. }  
Custom styling

I have applied some custom styles to some components, those are below.

home.component.scss
  1. .container {  
  2.     border: 1 px solid# f89090;  
  3.     margin: 5 % ;  
  4.     overflow: auto;  
  5.     width: 40 % ;  
  6.     height: 500 px;  
  7. }  
  8. app - movie {  
  9.     cursor: move;  
  10.     width: 50 % ;  
  11.     display: inline - flex;  
  12. }  
movie.component.scss
  1. mat - card {  
  2.     width: 70 % ;  
  3.     padding: 26 px;  
  4.     margin: 5 px;  
  5.     border: 1 px solid;  
  6. }  
Output

Once you have implemented all the steps, you will be having an application which uses Angular 7 Drag and Drop with actual server data. Now, let us run the application and see it in action.

New Angular Drag and Drop Feature ngDragDrop
ngDragDrop Initial
 
New Angular Drag and Drop Feature ngDragDrop
ngDragDrop After Adding
 
New Angular Drag and Drop Feature ngDragDrop
ngDragDrop adding more
 
Conclusion

In this post, we have learned how to,

  1. Create an Angular 7 application
  2. Work with Angular CLI
  3. Generate a service in Angular
  4. How to fetch data from the server using HttpModule
  5. Generate components in Angular
  6. Use Material design
  7. Work with Angular 7 Drag and Drop feature with real server data

Please feel free to play with this GitHub repository. Please do share your findings while you work on the same. I really appreciate that, thanks in advance.

Your turn. What do you think?

Thanks a lot for reading. I will come back with another post on the same topic very soon. Did I miss anything that you may think is needed? Did you find this post useful? If yes, please like/share/clap for me.