Adam Daniels

Adam Daniels

1554176855

How to use the infinite virtual scroll tool in the Angular Material Component Development Kit?

#angular #typescript #web-development

What is GEEK

Buddha Community

Edward Jackson

1554177019

Introduction

Angular is a JavaScript (TypeScript) framework for building web applications, mobile or desktop with over 42,000 stars️ on GitHub. It is maintained by the Angular team at Google and a host of community members and organizations. Angular version 7.0 was released some months ago. One of the features it shipped with is the virtual scroll tool in the Component Development Kit.

Component Development Kit (CDK)

The Component Development Kit is a set of tools that implement common behaviors and components with very unique interaction styles without being opinionated about the template choices. It is a kind of abstraction of the Angular Material Library, with no styling specific to material design. It provides more unique ways to get creative while building your Angular components.

Understanding the process

Most times when we work with really long lists in our presentation layer in Angular, we think of additional features to make the experience better. This can be like adding pagination or “next” button or even a “load more” button. The Component Development Kit has a scrolling feature that now helps us to have a better and more dynamic way of rendering these long lists of items in a way that is most efficient and with the lowest cost.

What you will learn

By building different fragments of a long list in this tutorial with the virtual scrolling CDK you will learn how to use basic best practises of using Angular and the Component Development Kit to build dynamic lists that will load and remove list items from the DOM just by scrolling. You get to see only the subset of the list you want to see at a particular time both on your frontend and in the DOM.

Prerequisites

To be able to follow through in this article’s demonstration you should have:

  • Node version 11.0 installed on your machine.
  • Node Package Manager version 6.7 (usually ships with Node installation).
  • Angular CLI version 7.0
  • The latest version of Angular (version 7)
    // run the command in a terminal
    ng version


Confirm that you are using version 7, and update to 7 if you are not. Other things that will be nice-to-haves are:

  • Node version 11.0 installed on your machine.
  • Node Package Manager version 6.7 (usually ships with Node installation).
  • Angular CLI version 7.0
  • The latest version of Angular (version 7)

Setting up

We will go through the process of setting up the development environment and installing all the required dependencies for the Component Development Kit to work.

Generating an Angular 7 application

    //cd to a preferred location
    // run the command below
    ng new virtualscroll


You do not need Angular routing, but you have to choose CSS for styling. Now, we get Angular Material installed on the above app

    ng add @angular/material


You can choose any pre-built theme of your choice or create one yourself (we used indigo-pink). For this tutorial, you do not need HammerJs or the Animations module. Angular Material ships with the Component Development Kit where our virtual scrolling module is located. Then, import the scrolling module in the app module so it is available for use in the Angular application so that the import section will look like so:

    // src/app/app.module.ts
    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { AppComponent } from './app.component';
    import { ScrollingModule } from '@angular/cdk/scrolling'
    import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
    import { ArtistsComponent } from './artists/artists.component';

Add this the scrolling module to the import section so it would look like this:

    imports: [BrowserModule,
             ScrollingModule
           ]

Creating a list

We will create an exportable data object in a new file we will call data.ts ``and then use an Angular service to expose the data to any component that imports it.

Create a new file in the app folder called data.ts and then populate it with artists like thus:

    // src/app/data.ts

    export const artists = [
    {
    number: "1",
    name: "Davido"
    },
    {
    number: "2",
    name: "Wizkid"
    },
    {
    number: "3",
    name: "Burna Boy"
    },
    {
    number: "4",
    name: "Patoranking"
    },
    {
    number: "5",
    name: "Maleek Berry"
    },
    {
    number: "6",
    name: "Mr. Eazi",
    },
    {
    number: "7",
    name: "Mayorkun"
    },
    {
    number: "8",
    name: "Peruzzi"
    },
    {
    number: "9",
    name: "Teni"
    },
    {
    number: "10",
    name: "Olamide"
    },
    {
    number: "11",
    name: "Phyno"
    },
    {
    number: "12",
    name: "M.I"
    },
    {
    number: "13",
    name: "Ycee"
    },
    {
    number: '14",
    name: "Dremo"
    },
    {
    number: "15",
    name: "Zlatan"
    },
    {
    number: "16",
    name: "Reminnisce"
    },
    {
    number: "17",
    name: "Tiwa Savage"
    },
    {
    number: "18",
    name: "Seyi Shay"
    },
    {
    number: "19",
    name: "Blaqbonez"
    },
    {
    number: "20",
    name: "Tekno"
    },
    {
    number: "21",
    name: "Niniola"
    }
    ]

Create a service called artists with this command in your project terminal:

    ng g service artists


This generates a service called artists in your app component. You can add the flag to remove the test spec file like this:

    ng g service --skipTests artists 


You should see a new file in the app folder called artists.service.ts ``and it should look like this:

    // src/app/artists.service.ts

    import { Injectable } from ‘@angular/core’;
    import { artists } from './data'
    @Injectable({
    providedIn: ‘root’
    })
    export class ArtistsService {
     constructor() { }
    }

To bring in the data to be used by the artists service, we return artists (as specified in the export statement in the data) in the constructor like so:

    // src/app/artists.service.ts

    export class ArtistsService {
     constructor() { }
      getArtists(){
       return artists;
       }
     }

Now we have to create a component for the artists where we can populate the hard coded data we have. Run the command below:

    ng g component -skipTests artists


This creates a component called artists and we can then pull the data on the artists service to the artists component using the lifecycle method when the component initializes like this:

    // src/app/artists/artists.component.ts 
    import { Component, OnInit } from '@angular/core';
    import { ArtistsService } from '../artists.service';
    @Component({
      selector: 'app-artists',
      templateUrl: './artists.component.html',
      styleUrls: ['./artists.component.css']
    })
    export class ArtistsComponent implements OnInit {
     constructor(private artistsService: ArtistsService) { }
      artists = [];
      ngOnInit() {
       this.getArtists();
      }
      getArtists (){
       this.artists = this.artistsService.getArtists();
       }
     }

Clear everything currently in the app.component.html and just replace with this selector instead:

    <app-artists></app-artists>

Creating items

Now that we have brought in the data through the artists service, let’s deal with the presentation and styling. To implement virtual scrolling in the user interface, Angular provides an HTML-like tag that tells Angular that the content inside the tag will have virtual scrolling implemented.

That is the <cdk-virtual-scroll-viewport> tag and when you want to use the virtual scrolling feature, Angular provides a special ngFor for you to use instead of the regular one. It is called *cdkVirtualFor and it does exactly the same thing as ngFor only that ngFor can not be used inside the virtual scroll tag.

It is compulsory to set the itemSize property on the viewport, as it will return an error if omitted.
*cdkVirtualFor has a few variables you can use for logic on your template:

  • Node version 11.0 installed on your machine.
  • Node Package Manager version 6.7 (usually ships with Node installation).
  • Angular CLI version 7.0
  • The latest version of Angular (version 7)

It is important to note that all these variables apply to the item index in the data source not in the rendered data. Normally, to display the artists, we have to use ngFor syntax like this:

    // src/app/artists/artists.component.html
    <div class="container">
      <h2>Brits Performing artists</h2>
      <div class="example-viewport">
        <div *ngFor="let artist of artists" class="list">
          <h2>{{artist.name}}</h2>
        </div>
      </div>
    </div>

Now, we use the virtual scroll syntax like this:

    // src/app/artists/artists.component.ts 
    <div class="container">
      <h2>Brits Performing artists</h2>
      <cdk-virtual-scroll-viewport itemSize="100" class="example-viewport">
     <div *cdkVirtualFor="let artist of artists" class="list">
       <h2>{{artist.name}}</h2>
      </div>
      </cdk-virtual-scroll-viewport>
    </div>

We can then style the viewport and the list items like this:

    // src/app/artists/artists.component.css

    .example-viewport{
     height: 250px;
     width: 25%;
     margin-left: 50px;
     border: 1px solid saddlebrown;
     display: flex;
    }
    .list{
     height: 50px;
     justify-content: center;
     align-items: center;
    }
    h2{
     margin-left: 40px;
    }
    .container{
     margin-bottom: 40px;
    }

You can now run your application in development environment with the command

    ng serve


Open your browser at http://localhost:4200/ and you should see your application like this:

If you take a look at the developer tools and inspect the elements section, you will notice that list items are added and removed from the DOM dynamically as you scroll. That is the awesome power of the virtual scrolling feature that shipped with the Component Development Kit.

Demo: a simple use case

If you have followed the article to this point, you must have by now started to have some ideas of how to implement the virtual scrolling feature in your next project. One of these use cases can be to create a hall of fame list featuring performers from the annual BRITs awards.

What we will be building

Coding the hall of fame

The few modifications made to achieve this demo above were done in the following component files: Add the following to the artists.component.html file:

    // src/app/artists/artists.component.html

    <h1>Brits Performance Hall of Fame</h1>
    <div class="container">
      <h2>2019 Artists</h2>
      <cdk-virtual-scroll-viewport itemSize="100" class="example-viewport">
      <div *cdkVirtualFor="let artist of artists" class="list">
        <h2>{{artist.number}}. {{artist.name}}</h2>
      </div>
      </cdk-virtual-scroll-viewport>
    </div>
    <div class="container">
      <h2>2018 Artists</h2>
      <cdk-virtual-scroll-viewport itemSize="100" class="example-viewport">
      <div *cdkVirtualFor="let artist of artists" class="list">
        <h2>{{artist.number}}. {{artist.name}}</h2>
      </div>
      </cdk-virtual-scroll-viewport>
    </div>
    <div class="container">
      <h2>2017 Artists</h2>
      <cdk-virtual-scroll-viewport itemSize="100" class="example-viewport">
      <div *cdkVirtualFor="let artist of artists" class="list">
        <h2>{{artist.number}}. {{artist.name}}</h2>
      </div>
      </cdk-virtual-scroll-viewport>
    </div>

Add the following to the artists.component.css file

    // src/app/artists/artists.component.css

    .example-viewport{
      height: 250px;
      width: 25%;
      margin-left: 50px;
      border: 1px solid saddlebrown;
      display: flex;
    }
    .list{
      height: 80px;
      justify-content: center;
      align-items: center;
    }
    h2{
      margin-left: 40px;
    }
    h1{
      margin-left: 18px;
    }
    .container{
      margin-bottom: 40px;
      display: flex;
    }

Add the following to the artists.components.ts file

    import { Component, OnInit } from '@angular/core';
    import { ArtistsService } from '../artists.service';
    @Component({
    selector: 'app-artists',
    templateUrl: './artists.component.html',
    styleUrls: ['./artists.component.css']
    })
    export class ArtistsComponent implements OnInit {
     constructor(private artistsService: ArtistsService) { }
      artists = [];
      ngOnInit() {
      this.getArtists();
    }
    getArtists (){
      this.artists = this.artistsService.getArtists();
      }
     }

Your application should now be up to date with our demo, you can now run it in the development environment

    ng serve


Conclusion

The Component Development Kit provides a lot of features that helps developers enhance the development process of the user interface. This tutorial gives you a quick guide to the syntax and usage of the virtual scrolling feature. You can find the official documentation here. You can download the code in this tutorial from here. Documentation for other Angular Material CDK features can be found here.

Happy Coding!

Learn More

Angular 7 (formerly Angular 2) - The Complete Guide

Angular & NodeJS - The MEAN Stack Guide

Learn and Understand AngularJS

The Web Developer Bootcamp

Ionic 4, Angular 7 and Cordova Crop and Upload Image

Angular 7 Routing Tutorial with Example

Build a CRUD App with Angular and Firebase

Angular Authentication Tutorial

Top 3 Useful TypeScript Tips for Angular

AngularJS tutorial for beginners with NodeJS, ExpressJS and MongoDB

MEAN Stack Tutorial MongoDB, ExpressJS, AngularJS and NodeJS

*Originally published by Lotanna Nwose at *https://pusher.com

Ajay Kapoor

1624334049

Top Angular JS Development Company in India | Angularjs Development

Save up to 60% of development cost and also get state-of-art infrastructure, experienced AngularJS web development team and latest technologies development.

Agile & DevOps Approach for on-time delivery
Strict NDA terms to ensure complete privacy
Flexible engagement models as per your needs
100% money-back guarantee, if not satisfied

Angularjs development company in India

#angular js development company #angular js web development #angular js development company in india #angular development company in india #angular development india #angular development company india

sophia tondon

sophia tondon

1620731241

Hire Top Angular Developers | Hire Angularjs Developer India

Looking to hire top dedicated Angular developers from India at affordable prices? Our First Time Right Angular JS developers build scalable, secure, robust and dynamic web applications while saving up to 60% of your development cost.

You can hire Angular development company on a monthly, hourly, or full-time basis who stay updated with the latest versions and ensure to deliver top-rated bespoke web applications.

Planning to outsource web services using Angular? Or would you like to hire a team of Angular developers? Get in touch for a free consultation!

Visit Website-https://www.valuecoders.com/hire-developers/hire-angularjs-developers

#angular developer #angular js developer #angular js developers #hire angular developer #hire angularjs developers #hiring angular developer

sophia tondon

sophia tondon

1620895296

Hire Top Angular Developers | Hire Angularjs Developer India

Looking to hire top and dedicated Angular developers at affordable prices? Our First Time Right Angular JS developers build scalable, secure, robust and dynamic web applications while saving up to 60% of your development cost.

You can hire Angular developers with 4+ years of average experience on a monthly, hourly, or full-time basis who stay updated with the latest versions and ensure to deliver top-rated bespoke web applications.

Planning to outsource Angular JS development company? Or would you like to hire a team of Angular developers? Get in touch for a free consultation!

##hire dedicated angularjs developer #angularjs development company #hire angular developer #hire angular developers #hire angular js developers #hire angular js developer

Why Choose Angular JS Development for Perfect Web Apps Development?

AngularJS is a JavaScript framework, this was developed by Google. IT is an open-source framework. AngularJS is responsible for handling all the activities and interactive elements on a web page. The main purpose of this framework is to develop applications for one single page. Angular JS highlights the testability process and the quality of codes for web pages. This is one of the main reasons why so many developers prefer this framework over others. Angular JS frameworks have been used in some of the top software development companies.The demand for AngularJS has been growing in all industries. This software system is fast and has helped solve the errors and mistakes of website projects. You can easily hire Angular JS developers team from the market or hire a freelancer for your work. Angular JS is the fastest and easiest framework of JavaScript to integrate with other frameworks. If you hire AngularJS developer you can easily make any kind of front-end website development easy. Why should you choose Angular JS for developing your web application? The main reason is that AngularJS has a lot of benefits, these will help you develop the best quality app. To read more click on the link.

#hire angular js developer #hire dedicated angular js developer #angular js application development #hire dedicated angular js team #hire best angular js application developer #website developer

Custom AngularJS Web App Development Company in USA

Looking for the best custom AngularJS app development company? AppClues Infotech is a top-rated AngularJS app development company in USA producing robust, highly interactive and data-driven AngularJS web and mobile applications with advanced features & technologies.

For more info:
Website: https://www.appcluesinfotech.com/
Email: info@appcluesinfotech.com
Call: +1-978-309-9910

#custom angular js web app development company in usa #best angular js app development company in usa #hire angular js app developers in usa #top angular js app development company #professional angular js app developers #leading angular js app development agency