As you all know, Angular 7 is out with some cool new features.
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!
The source code can be found here.
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.
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
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>
header.component.html
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>
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]
})
app-routing.module.ts
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>
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 { }
app.module.ts
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.
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();
}
}
MovieService.ts
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.
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 };
Config.ts
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>
MovieComponent.html
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() {
}
}
MovieComponent.ts
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.
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>
HomeComponent.html
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.cdkDropList
container, we’re looping through the values and pass the movie to our own movie component, which is app-movie
.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.
<div cdkDropList #towatch="cdkDropList" [cdkDropListData]="moviesToWatch" [cdkDropListConnectedTo]="[allmovies]" (cdkDropListDropped)="drop($event)">
<app-movie *ngFor="let movie of moviesToWatch" [movie]="movie" cdkDrag></app-movie>
</div>
moviesToWatch.html
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>
home.component.html
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);
}
}
}
home.component.ts
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);
}
}
DropEvent.ts
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);
}
}
}
home.component.ts
I have applied custom styles to some components, you can see those below.
.container{
border: 1px solid rgb(248, 144, 144);
margin: 5%;
overflow: auto;
width: 40%;
height: 500px;
}
app-movie{
cursor: move;
width: 50%;
display: inline-flex;
}
home.component.scss
mat-card{
width: 70%;
padding: 26px;
margin: 5px;
border: 1px solid;
}
movie.component.scss
After implementing all the steps above, you’ll have an application which uses Angular 7 drag and drop with actual server data.
Let’s run the application and see it in action.
ngDragDrop Initial
ngDragDrop after adding
ngDragDrop adding more
The demo can be found on GitHub.
In this post, we learned how to:
HttpModule
.Feel free to play around with the GitHub repository.
Thanks for reading. I will write another post on the same topic in the future.
#angular #angularjs #javascript #Angular 7 #Drag