Skip to main content

New Angular Drag and Drop Feature — ngDragDrop

 I’m going to explain one of Angular 7’s features — Drag and Drop.

In this article, we’ll build an application which fetches data from the database and binds it to the UI. It will then perform multi-directional drag and drops.

Let’s start!

Source Code

The source code can be found here.

Install Angular CLI

As you may have guessed, we are using Angular CLI.

If you haven’t yet installed Angular CLI, I recommend you install it now. It is a great CLI tool for Angular, I’m sure you’ll enjoy it.

You can install it by running this command:

npm install -g @angular/cli

Once we set up this project, we will be using the Angular CLI commands. The Angular CLI documentation will help you understand all the things you can do with CLI.

Generate a New Project

It is time to generate our new project. We can use the command below.

ng new ngDragDrop

You will now be able to see all the hard work CLI does for us.

Now that we have created our application, let’s run it to see if it is working or not.

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

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

As we develop, we will be using the Angular material for the design.

We can install it now, along with the animation and CDK. With Angular 6+ versions you can also do this with this command:

ng add @angular/material

Generate and Set Up the Header Component

We now have an application to work with — let’s create a header component.

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 only editing the HTML of the header component for myself and I’m not going to add any logic. You can add anything you wish.


<div style="text-align:center">
  <h1>
    Welcome to ngDragDropg at <a href="https://sibeeshpassion.com">Sibeesh Passion</a>
  </h1>
</div>

Set Up the Footer Component

Create the footer component by running the following command:

ng g c footer

You can edit or style them as you wish.

<p>
Copyright @SibeeshPassion 2018 - 2019 :)
</p>

Set Up app-routing.module.ts

We are only going to create a route for home.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
const routes: Routes = [
  {
    path: '',
    redirectTo: '/home',
    pathMatch: 'full'
  },
  {
    path: 'home',
    component: HomeComponent
  }
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }Set Up Router Outlet in app.component.html

We now have a route and it is time to set up the outlet.

<app-header></app-header>
<router-outlet>
</router-outlet>
<app-footer></app-footer>

Set Up app.module.ts

Every Angular app will have at least one NgModule class — AppModule resides in app.module.ts.

You can learn more about Angular architecture on Angular’s website.















































import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { MatButtonModule, MatCheckboxModule, MatMenuModule, MatCardModule, MatSelectModule } from '@angular/material';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { FooterComponent } from './footer/footer.component';
import { HomeComponent } from './home/home.component';
import { MovieComponent } from './movie/movie.component';
import { MovieService } from './movie.service';
import { HttpModule } from '@angular/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { DragDropModule } from '@angular/cdk/drag-drop';
@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    FooterComponent,
    HomeComponent,
    MovieComponent
  ],
  exports: [
    HttpModule,
    BrowserModule,
    AppRoutingModule,
    DragDropModule,
    MatButtonModule, MatCheckboxModule, MatMenuModule, MatCardModule, MatSelectModule, BrowserAnimationsModule
  ],
  imports: [
    HttpModule,
    BrowserModule,
    AppRoutingModule,
    DragDropModule,
    MatButtonModule, MatCheckboxModule, MatMenuModule, MatCardModule, MatSelectModule, BrowserAnimationsModule
  ],
  providers: [MovieService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Do you see a DragDropModule there?

You should import it to use the drag and drop feature — it resides in the @angular/cdk/drag-drop.

As you might have noticed, we have added a service called MovieService in the provider’s array. We will create it now.

Create a Movie Service

import { Injectable } from '@angular/core';
import { RequestMethod, RequestOptions, Request, Http } from '@angular/http';
import { config } from './config';
@Injectable({
  providedIn: 'root'
})
export class MovieService {
  constructor(private http: Http) {
  }
async get(url: string) {
    return await this.request(url, RequestMethod.Get);
  }
async request(url: string, method: RequestMethod) {
    const requestOptions = new RequestOptions({
      method: method,
      url: `${config.api.baseUrl}${url}${config.api.apiKey}`
    });
const request = new Request(requestOptions);
    return await this.http.request(request).toPromise();
  }
}

As you can see, 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. In this article and the repository, I am using mine. I strongly recommend you create your own instead of using the one mentioned here.

Let’s set up the config file now.

Set Up config.ts

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

































const config = {
    api: {
        baseUrl: 'https://api.themoviedb.org/3/movie/',
        apiKey: '&api_key=c412c072676d278f83c9198a32613b0d',
        topRated: 'top_rated?language=en-US&page=1'
    }
};
export { config };

Create a Movie Component

Let’s create a new component now to load the movie into.

Basically, we will use this movie component inside the cdkDropList div.

Our movie component will have HTML as below.

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

I just made it as simple as possible. In the future, we can add a few more properties for the movie component and show them here.

The TypeScript file will have one property with the @Input decorator so that we can input the values from the home component.

import { Component, OnInit, Input } from '@angular/core';
import { Movie } from '../models/movie';
@Component({
  selector: 'app-movie',
  templateUrl: './movie.component.html',
  styleUrls: ['./movie.component.scss']
})
export class MovieComponent implements OnInit {
  @Input()
  movie: Movie;
  
  constructor() { 
  }
ngOnInit() {
  }
}

Here is my model movie:

export class Movie {
poster_path: string;
}

As I said, it has only one property at the moment, I will add a few later.

Set Up the Home Component

This is the main part; the place where we render our movies and perform drag and drop.

I will have a parent container as <div style="display: flex;"> so that the inner divs will be arranged horizontally.

I’ll have two inner containers: one to show all the movies and another 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. Below is the whole movie collection.



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

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

  • 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’re connecting two app-movie containers. Remember that 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’s a drag and drop event.
  • Inside the cdkDropList container, we’re 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.

Let’s create another container which will consist of the collection of movies I am going to watch.

We’re almost using the exact same properties as we did for the first container, except for the IDs — cdkDropListData and cdkDropListConnectedTo.

Finally, our home.component.html will be as follows:

<div style="display: flex;">
  <div class="container">
    <div class="row">
      <h2 style="text-align: center">Movies</h2>
      <div  cdkDropList #allmovies="cdkDropList" [cdkDropListData]="movies" [cdkDropListConnectedTo]="[towatch]"
        (cdkDropListDropped)="drop($event)">
        <app-movie *ngFor="let movie of movies" [movie]="movie" cdkDrag></app-movie>
      </div>
    </div>
  </div>
  <div class="container">
    <div class="row">
      <h2 style="text-align: center">Movies to watch</h2>
      <div cdkDropList #towatch="cdkDropList" [cdkDropListData]="moviesToWatch" [cdkDropListConnectedTo]="[allmovies]"
        (cdkDropListDropped)="drop($event)">
        <app-movie *ngFor="let movie of moviesToWatch" [movie]="movie" cdkDrag></app-movie>
      </div>
    </div>
  </div>
</div>

Now we need to get some data by calling our service.

Let’s open our home.component.ts file.

import { Component } from '@angular/core';
import { MovieService } from '../movie.service';
import { Movie } from '../models/movie';
import { config } from '../config';
import { CdkDragDrop, moveItemInArray, transferArrayItem } from '@angular/cdk/drag-drop';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent {
  movies: Movie[];
  moviesToWatch: Movie[] = [{
    poster_path: '/uC6TTUhPpQCmgldGyYveKRAu8JN.jpg'
  }];
  constructor(private movieService: MovieService) {
    this.getMovies();
  }
  private async getMovies() {
    const movies = await this.movieService.get(config.api.topRated);
    return this.formatDta(movies.json().results);
  }
  formatDta(_body: Movie[]): void {
    this.movies = _body.filter(movie => movie.poster_path !== '/uC6TTUhPpQCmgldGyYveKRAu8JN.jpg');
  }
  drop(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);
    }
  }
}

Here, I’m importing CdkDragDrop, moveItemInArray, and transferArrayItem from ‘@angular/cdk/drag-drop’. This helps us to perform the drag and drop.

In the constructor, we’re fetching the data and assigning it to the variable movies. These are an array of the movie.

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

I’m setting the “movies to watch” collection as below, as I already planned to watch that movie.

moviesToWatch: Movie[] = [{
poster_path: '/uC6TTUhPpQCmgldGyYveKRAu8JN.jpg'
}];

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

formatDta(_body: Movie[]): void {
this.movies = _body.filter(movie => movie.poster_path !== '/uC6TTUhPpQCmgldGyYveKRAu8JN.jpg');
}

And below is our drop event.

drop(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 complete code for home.component.ts will look like this:

import { Component } from '@angular/core';
import { MovieService } from '../movie.service';
import { Movie } from '../models/movie';
import { config } from '../config';
import { CdkDragDrop, moveItemInArray, transferArrayItem } from '@angular/cdk/drag-drop';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent {
  movies: Movie[];
  moviesToWatch: Movie[] = [{
    poster_path: '/uC6TTUhPpQCmgldGyYveKRAu8JN.jpg'
  }];
  constructor(private movieService: MovieService) {
    this.getMovies();
  }
  private async getMovies() {
    const movies = await this.movieService.get(config.api.topRated);
    return this.formatDta(movies.json().results);
  }
  formatDta(_body: Movie[]): void {
    this.movies = _body.filter(movie => movie.poster_path !== '/uC6TTUhPpQCmgldGyYveKRAu8JN.jpg');
  }
  drop(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);
    }
  }
}





























































Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...