DHTMLX Gantt with Angular 4 and Socket.io

In this demo I’m going to be looking at using the Gantt Chart from DHTMLX inside an Angular 4 app using Socket IO to synchronize connected clients.

The DHTMLX Gantt is a component from DHTMLX who produce third pary components, one of which is the Gantt chart we’ll be using.

DHTMLX Gantt Chart Basic
DHTMLX Gantt Chart Basic

We’ll be using Socket.io which according to the website “Socket.IO enables real-time bidirectional event-based communication” – we’ll be using that to synchronize clients that are using the Gantt Chart real time. This means that if user A changes a task, user B will see those changes reflected real time.

socket.io
socket.io

First let’s set up and Angular 4 app using the Angular CLI (If you don’t have it follow my tutorial

http://malcolmswaine.com/2017/11/get-angular-4-nodejs-site-running-minutes/

As with most of my other demo’s I like to start in C:\demos on my local machine

Demos Directory
Demos Directory

navigate to the folder using a command prompt

Demos Directory Command
Demos Directory Command

from the command prompt let’s create a new Angular 4 app called ngSocketIOGantt by running the command

ng new ngSocketIOGantt
Angular 4 New Project With CLI tool
Angular 4 New Project With CLI tool

When the command is complete we should have a new Angular 4 project in a folder structure as so

Angular4 SocketIO DXHTML Gantt Folder Stucture
Angular4 SocketIO DXHTML Gantt Folder Stucture

The way we’re going to do this is to have two server processes running – one on port 8080 for servicing Socket IO clients and one other on port 4200 for serving regular static files.

First let’s create the server side bits we need to get up and running.

From the command prompt, drop into the ngSocketIOGantt directory that the Angular CLI tool created for us

cd ngSocketIOGanttOGantt

and install the NPM packages we’ll need to start servicing Socket IO connections.

npm install express socket.io --save
Install SocketIO Express on NodeJS
Install SocketIO Express on NodeJS

When the process has finished, create new file called app.js in the ngSocketIOGantt folder. NodeJS is going use this file to set up Socket IO configuration and event handling.

Create NodeJS App For Socket.IO
Create NodeJS App For Socket.IO

Next edit the app.js file (I’m using sublime text here) add the following script

var express = require('express');
var path = require('path');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var port = 8080;

app.use(express.static(path.join(__dirname, "src")));

io.on('connection', function(socket){
  console.log('new connection made');

  socket.emit('get-model', 
   {
     data: 
     [
       {id: 1, text: "Task #1", start_date: "2017-04-15 00:00", duration: 3, progress: 0.6}, 
       {id: 2, text: "Task #2", start_date: "2017-04-18 00:00", duration: 3, progress: 0.4}
     ],
     links:
     [ 
       {id: 1, source: 1, target: 2, type: "0"} 
     ]
   }
    );

  socket.on('send-model', function(updatedModel){
    console.log(updatedModel);
    socket.broadcast.emit('get-model', updatedModel);
  });
})

server.listen(port, function(){
  console.log("Listening on port " + port);
});

console.log("Node started");

At the top of the script we use require to obtain the Socket.IO library passing server instance we instantiated

var io = require('socket.io')(server);
var port = 8080;

We then declare the port we’re going to listen on

We the handle any connection events

io.on('connection', function(socket){

and upon a client connecting to the service we immedaitely send out some dummy data – obviously we wouldn’t do this in production, we would load from our database, but for the sake of keeping things simple we’ll just pass back hard coded data for now

socket.emit('get-model', 
   {
     data: 
     [
       {id: 1, text: "Task #1", start_date: "2017-04-15 00:00", duration: 3, progress: 0.6}, 
       {id: 2, text: "Task #2", start_date: "2017-04-18 00:00", duration: 3, progress: 0.4}
     ],
     links:
     [ 
       {id: 1, source: 1, target: 2, type: "0"} 
     ]
   }

We then set up and handler for when a client has changed the Gantt Chart and would like to push those changes to all connected clients. In this case we just take the data that been modified by the client and push it back out again to every client except the client that sent it

socket.on('send-model', function(updatedModel){
    console.log(updatedModel);
    socket.broadcast.emit('get-model', updatedModel);
  });

Your complete file should look something like this

Node Socket.IO DHTMLX Server
Node Socket.IO DHTMLX Server

Next let’s move onto the Angular client setup

Before we do anything, let’s add the Gantt packages for Node through NPM

Open up a command prompt and navigate to our newly created angular Project root directory. From there create run the following NPM commands

npm install dhtmlx-gantt --save
npm install @types/dhtmlxgantt --save 
Save NPM DHTMLX Gantt Packages
Save NPM DHTMLX Gantt Packages

Let’s also add the associated styling by including it into our styles.css. Open the file styles.css in the src directory with an editor

Add Gantt style to styles.css
Add Gantt style to styles.css

and add the following code

@import "../node_modules/dhtmlx-gantt/codebase/dhtmlxgantt.css";
DHTML Gantt Style Import
DHTML Gantt Style Import

Next let’s create an Angular Service to connect with our Socket.IO backend to send and receive data. In our src\app directory create a file called gantt.service.ts

Create DHTMLX Gantt Angular4 Service
Create DHTMLX Gantt Angular4 Service

Edit the file and paste in the following TypeScript


import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
import * as io from 'socket.io-client';

export class GanttService {
  // Our localhost address that we set in our server code
  private url = 'http://localhost:8080'; 
  private socket;

   sendModel(model)
   {
    this.socket.emit('send-model', model);   
   }

   getModel() 
   {
    let observable = new Observable(observer => {
      this.socket = io(this.url);
      this.socket.on('get-model', (data) => {
        
        console.log('in gantt service get model');
        observer.next(data);   
      });
      return () => {
        this.socket.disconnect();
      }; 
    })    
    return observable;
  } 
}

In summary, we start by importing the necessary Reactive Extensions

import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';

Next I get the socket IO libraries

import * as io from 'socket.io-client';

We declare that we need to connect to the Socket IO server on port 8080

private url = 'http://localhost:8080';

Then we declare a method to take the data that makes up the entries in our Gantt and send it back to the Socket IO server to propagate to anyone else that is listening

sendModel(model)
   {
    this.socket.emit('send-model', model);   
   }

Then we create a method to build and Observable and subscribe to the Socket IO

let observable = new Observable(observer => {
      this.socket = io(this.url);

and handle when the server sends the get-model event

this.socket.on('get-model', (data) => {

calling

observer.next(data);

will cause the any code that has subscribed to the Observable to be called passing the data as a parameter
 

Next let’s add the Gantt inside a new component that we can use as a directive

Create a new file called gantt.component.ts inside the src/app directory

Create New DHTMLX Gantt Component typescript
Create New DHTMLX Gantt Component typescript

Paste the following code into the file


import {Component, ElementRef, OnInit, ViewChild} from "@angular/core";
import "dhtmlx-gantt";
import {GanttService} from "./gantt.service";

import {} from "@types/dhtmlxgantt";

@Component({
    selector: "gantt",
    styles: [
        `
        :host{
            display: block;
            height: 600px;
            position: relative;
            width: 100%;
        }
    `],
    providers: [GanttService],
    template: "<div #gantt_here style='width: 100%; height: 100%;'></div>",
})
export class GanttComponent implements OnInit {
    @ViewChild("gantt_here") ganttContainer: ElementRef;

    connection;

    constructor(private ganttService: GanttService){
    }

    ngOnInit(){
        gantt.config.xml_date = "%Y-%m-%d %H:%i";
        gantt.init(this.ganttContainer.nativeElement);
        var that = this;

        gantt.attachEvent("onAfterTaskUpdate", function(id,item){            
            console.log('onAfterTaskUpdate ' + id);
            let ganttJson = gantt.serialize();
            that.ganttService.sendModel(ganttJson);
        });

       this.connection = this.ganttService.getModel().subscribe(data => {           
            console.log('getModel');
            console.log(data);           
            gantt.parse(data);            
       })
    }
}

I start by importing from Angular Core

  • ElementRef – A Dom reference to an element in our HTML
  • OnInit – We want to run our code when when Angular has finished setting up
  • ViewChild – We want to be able to reference child components

In the component decorator we register our Gantt Service and declare the markup we’re going to use as a template

providers: [GanttService],
template: "<div #gantt_here style='width: 100%; height: 100%;'></div>",

In our class declaration we get a reference to the Gantt we using as a child component

@ViewChild("gantt_here") ganttContainer: ElementRef;

Next we set the date format for the Gantt and initialize it

gantt.config.xml_date = "%Y-%m-%d %H:%i";
gantt.init(this.ganttContainer.nativeElement);

Whenever we change a task we want to propagate the event to the other client that are attached to this service, so handle the event onAfterTaskUpdate, serialize the data that forms the model for the gantt and then call the sendModel method we implemented in the GanttService sending our data. This will then send the same model to all the other gantt charts and they will all be updated with the same corresponding changes

gantt.attachEvent("onAfterTaskUpdate", function(id,item){            
            console.log('onAfterTaskUpdate ' + id);
            let ganttJson = gantt.serialize();
            that.ganttService.sendModel(ganttJson);
        });

Finally we subscribe to whenever socket io want to notify us that another client has changed the model

this.connection = this.ganttService.getModel().subscribe(data => {           
            console.log('getModel');
            console.log(data);           
            gantt.parse(data);            
       })

Edit the Angular app.module file so that we can import the necessary modules for supporting our gantt

Edit Angular App Module
Edit Angular App Module

Paste the following code into the app.module.ts file

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { GanttComponent} from "./gantt.component";

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

Finally let’s add the component deceleration into our HTML. Edit the app.component.html file

and replace the market with the following

<div style="text-align:center">
  <h1>
    Welcome to {{title}}!
  </h1>
  <gantt></gantt>
 </div> 

We should be good to go now

Start the Socket IO we set up by opening a command prompt at the root of the project we created

Change To SocketIO Gantt Directory
Change To SocketIO Gantt Directory

And start node by running

node app.js
Start SocketIO
Start SocketIO

Next start the our second service to run our angular – again from our project root

npm start
NPM Start
NPM Start

This should start a server listening on port 4200

.** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **

Open two browser windows on the url http://localhost:4200/

Try changing the tasks in one of the windows – the corresponding task in the other window should move real time.

Gantt Socket.IO moves real time
Gantt Socket.IO moves real time

The full source code can be found at

https://github.com/malcolmswainecom/DXHTML-SocketIO-Angular4

Leave a Reply

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