Skip to main content

Angular 7 – Virtual Scrolling and Drag and Drop features

Angular 7 is out!! Angular Material received a big update in this year and the two new features of Angular CDK, Virtual Scrolling and Drag and Drop support are now available with Angular 7. Virtual Scrolling loads and unloads elements from the DOM based on the visible parts of a list, where Drag and Drop feature supports dragging, dropping and rearranging elements. In this post, we will look at Virtual Scrolling and Drag and Drop features in action with Angular 7.

Angular 7 – Virtual Scrolling and Drag and Drop features

If you want to learn all of Angular, I want to personally recommend ng-book as the single-best resource out there. You can get a copy here. The book is updated to Angular 7.

Before we create the Angular 7 app, we need to update the Angular CLI to the latest version. To update Angular CLI, run the following command,

npm install -g @angular/cli

Once it is installed, check the version of Angular CLI. It should be greater than 7.

Update Angular CLI to latest version

Next, create a new Angular 7 Web Application using this Angular CLI command.

ng new angular7-features

Once you hit this command, Angular CLI prompts to add routing or style sheet format. This is a new feature in Angular CLI. The Angular 7 application will be ready in few minutes.

Angular 7 – Virtual Scrolling and Drag and Drop features

Run this command to see the Angular 7 application in action.

ng serve

Open your browser, then go to this address `localhost:4200`, you should see this Angular 7 page. Let’s see both the features in action now.

Virtual Scrolling

Virtual Scrolling loads and unloads elements from the DOM based on the visible parts of a list, making it possible to build very fast experiences for users with very large scrollable lists. To implement Virtual Scrolling, we need to install the angular CDK package and import the ScrollingModule module. Install the module via npm:

npm install @angular/cdk@latest

Once the module is installed, run ng serve command to check the application is running properly or not.

Next, import the ScrollingModule module. To do that , open app.module.ts and make the highlighted code changes.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ScrollingModule } from '@angular/cdk/scrolling';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    ScrollingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Add the following HTML in app.component.html file.

<h2>Virtual Scrolling example</h2>
<cdk-virtual-scroll-viewport class="example-viewport"  itemSize="100">
  <div *cdkVirtualFor="let n of scrollItems"  class="example-item">Item {{n}}</div>
</cdk-virtual-scroll-viewport>

Next, we need to generate an Array to display items in the list. The following code in app.component.ts will create a number array and adds the item to the array.

export class AppComponent {
  title = 'Angular 7 – Virtual Scrolling and Drag and Drop features'; 
  scrollItems: number[] = [];
  constructor() {
    for (let index = 0; index < 10000; index++) {
      this.scrollItems.push(index);
    }
  } 
}

Add some styling to the elements.

 .example-viewport {
    height: 400px;
    width: 300px;
    border: 1px solid black;
  }
  
  .example-item {
    padding: 25px;
    background: rgb(171, 235, 52);
    margin-bottom: 2px;
    text-align: center;
    font-size: 20px;
  }

That’s it. Run your Angular app and you should see the following.

Angular 7 – Virtual Scrolling

As you can see, the app initially displays only a small subset of the items in the viewport and keep changing the items as you scroll. It keeps the number of DOM elements constant which results in better performance.

Drag and Drop

To use Drag and Drop feature, import the DragDropModule module. To do that , open app.module.ts and make the highlighted code changes.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ScrollingModule } from '@angular/cdk/scrolling';
import { DragDropModule } from '@angular/cdk/drag-drop';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    ScrollingModule,
    DragDropModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Add the following HTML in app.component.html file.

<h2>Drag and Drop example</h2>
<div class="box" cdkDrag>Drag me around!</div>
<br />
<div cdkDropList (cdkDropListDropped)="onDrop($event)">
  <div class="box" *ngFor="let item of items" cdkDrag>{{item}}</div>
</div>

Few points worth mentioning here:

  • You can create draggable component by using the cdkDrag directive.
  • You can add cdkDropList elements to constrain where elements may be dropped.
  • Adding cdkDropList around a set of cdkDrag elements groups the draggables into a reorderable collection. Items will automatically rearrange as an element moves. Note that this will not update your data model; you can listen to the cdkDropListDropped event to update the data model once the user finishes dragging.

Next, add these following CSS class in the style.css file. These classes styles the elements and provides animation while dragging and dropping.

.box {
  border: 1px solid black;
  padding: 20px;
  width: 200px;
  background-color:lightblue;
}

.cdk-drop-dragging .cdk-drag {
  transition: transform 500ms cubic-bezier(0, 0, 0.2, 1);
}

.cdk-drag-animating {
  transition: transform 550ms cubic-bezier(0, 0, 0.2, 1);
}

.cdk-drag-placeholder {
  background-color: Highlight;
}
  • Finally, open app.component.ts and place the highlighted code.

    import { Component } from '@angular/core';
    import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
    
    @Component({
      selector: 'app-home',
      templateUrl: './home.component.html',
    })
    export class HomeComponent {
      items = ['First', 'Second', 'Third', 'Fourth'];
    
      onDrop(event: CdkDragDrop<string[]>) {
        moveItemInArray(this.items, event.previousIndex, event.currentIndex);
      }
    }
    

    As you can see in the code snippet above, the drag and drop CDK comes with a function moveItemInArray. This function rearranges the items array according to the indexes. The onDrop event is called, when the item is dropped.

    That’s it. Run your Angular app and you should see the following.

    Angular 7 – Drag and Drop Feature

    You can find this demo here and code in action here.

    If you really want to master Angular 7, ng-book is the single-best resource out there. Get your copy here.

    Thank you for reading. Keep visiting this blog and share this in your network. Please put your thoughts and feedback in the comments section.

    PS: If you found this content valuable and want to return the favour, then Buy Me A Coffee
  • 2 thoughts to “Angular 7 – Virtual Scrolling and Drag and Drop features”

    Leave a Reply

    Your email address will not be published. Required fields are marked *