Getting started in EJ2 TypeScript Diagram control

4 Sep 202424 minutes to read

This section explains how to create a simple Diagram component and configure its available functionalities in TypeScript, using Essential JS 2 quickstart seed repository.

This application is integrated with the webpack.config.js configuration and uses the latest version of the webpack-cli. It requires node v14.15.0 or higher. For more information about webpack and its features, refer to the webpack documentation.

Dependencies

The following list of dependencies are required to use the Diagram component in your application.

|-- @syncfusion/ej2-diagrams
    |-- @syncfusion/ej2-base
    |-- @syncfusion/ej2-data
    |-- @syncfusion/ej2-navigations
    |-- @syncfusion/ej2-inputs
    |-- @syncfusion/ej2-popups
    |-- @syncfusion/ej2-buttons
    |-- @syncfusion/ej2-lists
    |-- @syncfusion/ej2-splitbuttons

Set up development environment

Open the command prompt from the required directory, and run the following command to clone the Syncfusion JavaScript (Essential JS 2) quickstart project from GitHub.

git clone https://github.com/SyncfusionExamples/ej2-quickstart-webpack- ej2-quickstart

After cloning the application in the ej2-quickstart folder, run the following command line to navigate to the ej2-quickstart folder.

cd ej2-quickstart

Add Syncfusion JavaScript packages

Syncfusion JavaScript (Essential JS 2) packages are available on the npmjs.com public registry. You can install all Syncfusion JavaScript (Essential JS 2) controls in a single @syncfusion/ej2 package or individual packages for each control.

The quickstart application is preconfigured with the dependent @syncfusion/ej2 package in the ~/package.json file. Use the following command to install the dependent npm packages from the command prompt.

npm install

Import the Syncfusion CSS styles

To render the Diagram component, need to import diagram and its dependent component’s styles as given below in the ~/src/styles/styles.css file, as shown below:

@import '../../node_modules/@syncfusion/ej2-diagrams/styles/material.css';
@import "../../node_modules/@syncfusion/ej2-base/styles/material.css";
@import "../../node_modules/@syncfusion/ej2-popups/styles/material.css";
@import "../../node_modules/@syncfusion/ej2-splitbuttons/styles/material.css";
@import "../../node_modules/@syncfusion/ej2-navigations/styles/material.css";

Module Injection

The diagram component is divided into individual feature-wise modules. In order to use a particular feature, inject the required module. The following list describes the module names and their description.

  • BpmnDiagrams: Inject this provider to add built-in BPMN shapes to diagrams.
  • ConnectorBridging: Inject this provider to add bridges to connectors.
  • ConnectorEditing: Inject this provider to edit the segments for connector.
  • ComplexHierarchicalTree: Inject this provider to complex hierarchical tree like structure.
  • DataBinding: Inject this provider to populate nodes from given data source.
  • DiagramContextMenu: Inject this provider to manipulate context menu.
  • HierarchicalTree: Inject this provider to use hierarchical tree like structure.
  • LayoutAnimation: Inject this provider animation to layouts.
  • MindMap: Inject this provider to use mind map.
  • PrintAndExport: Inject this provider to print or export the objects.
  • RadialTree: Inject this provider to use radial tree like structure.
  • Snapping: Inject this provider to snap the objects.
  • SymmetricLayout: Inject this provider to render layout in symmetrical method.
  • UndoRedo: Inject this provider to revert and restore the changes.
  • Ej1Serialization - Inject this provider to load ej1 diagram json in ej2 diagram.

These modules should be imported and injected into the Diagram component using Diagram.Inject method as follows.

import { Diagram, HierarchicalTree, MindMap, RadialTree, ComplexHierarchicalTree, DataBinding, Snapping, PrintAndExport, BpmnDiagrams, SymmetricLayout, ConnectorBridging, UndoRedo, LayoutAnimation, DiagramContextMenu, ConnectorEditing,Ej1Serialization } from '@syncfusion/ej2-diagrams';

Diagram.Inject(BpmnDiagrams, ConnectorBridging, ConnectorEditing, ComplexHierarchicalTree, DataBinding, DiagramContextMenu, HierarchicalTree, LayoutAnimation, MindMap, PrintAndExport, RadialTree, Snapping, SymmetricLayout, UndoRedo,Ej1Serialization);

Add diagram to the project

Add the HTML div element for the diagram into your index.html. [src/index.html]

<!DOCTYPE html>
<html lang="en">

<head>
    <title>EJ2 Diagram</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Typescript UI Controls" />
    <meta name="author" content="Syncfusion" />
    <link rel="shortcut icon" href="resources/favicon.ico" />
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
</head>

<body>
    <!--container which is going to render the Diagram-->
    <div id='container'>
    </div>
</body>

</html>

Now, import the diagram component into your app.ts to instantiate a diagram and append the diagram instance to the #container. [src/app/app.ts]

The following example shows a basic diagram.

 import { Diagram } from '@syncfusion/ej2-diagrams';
let diagram: Diagram = new Diagram({
    width: '100%', height: '600px'
});
diagram.appendTo('#element');

Now, the npm run start command is used to run the application in the browser.

npm run start

Basic Diagram elements

  • Node: Visualizes any graphical object using nodes, which can also be arranged and manipulated on a diagram page.
  • Connector: Represents the relationship between two nodes. Three types of connectors provided as follows:

1) Orthogonal
2) Bezier
3) Straight

  • Port: Acts as the connection points of node or connector and allows you to create connections with only specific points.
  • Annotation: Shows additional information by adding text or labels on nodes and connectors.

Flow Diagram

Create and add node to the diagram

Create and add a node (JSON data) with specific position, size.

import { Diagram, NodeModel } from '@syncfusion/ej2-diagrams';
// A node is created and stored in nodes array.
let nodes: NodeModel[] = [{
    // Unique name for the node
    id: "Start",
    // Position of the node
    offsetX: 300,
    offsetY: 50,
    // Size of the node
    width: 140,
    height: 50,
}];
// initialize Diagram component
let diagram: Diagram = new Diagram({
    width: '100%', height: '600px',
    // Add node
    nodes: nodes
});
// render initialized Diagram
diagram.appendTo('#element');
<!DOCTYPE html>
<html lang="en">

<head>
    <title>EJ2 Diagram</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Typescript UI Controls" />
    <meta name="author" content="Syncfusion" />
    <link href="index.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-buttons/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-popups/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-splitbuttons/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-diagrams/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-navigations/styles/fabric.css" rel="stylesheet" />
    <script src="systemjs.config.js"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>

<body>
    <div id='loader'>Loading....</div>
    <div id='container'>
        <div id='element'></div>
    </div>
</body>

</html>

Apply shape and style to node

Syncfusion diagram control provides support to render many built-in shapes in diagram.
Please refer to Shapes to know about built-in Shapes.

import { Diagram, NodeModel } from '@syncfusion/ej2-diagrams';
// A node is created and stored in nodes array.
let nodes: NodeModel[] = [{
        // Unique name for the node
        id: "Start",
        // Position of the node
        offsetX: 300,
        offsetY: 50,
        // Size of the node
        width: 140,
        height: 50,
        // Text(label) added to the node
        annotations: [{
            id: 'label1',
            content: 'Start'
        }],
        // Shape for the node
        shape: { type: 'Flow', shape: 'Terminator'},
        //To define border style for the node.
        borderColor:'orange',borderWidth:10,
        //To define style for the node.
        style:{fill:'red',strokeColor:'green',strokeWidth:5,strokeDashArray:'2 2'}
            }];
// initialize Diagram component
let diagram: Diagram = new Diagram({
    width: '100%', height: '600px',
    // Add node
    nodes: nodes
});
// render initialized Diagram
diagram.appendTo('#element');
<!DOCTYPE html>
<html lang="en">

<head>
    <title>EJ2 Diagram</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Typescript UI Controls" />
    <meta name="author" content="Syncfusion" />
    <link href="index.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-buttons/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-popups/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-splitbuttons/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-diagrams/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-navigations/styles/fabric.css" rel="stylesheet" />
    <script src="systemjs.config.js"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>

<body>
    <div id='loader'>Loading....</div>
    <div id='container'>
        <div id='element'></div>
    </div>
</body>

</html>

Add other flowchart nodes to the diagram

You can add multiple nodes with different shapes into diagram.

import { Diagram, NodeModel, ConnectorModel } from '@syncfusion/ej2-diagrams';
let nodes: NodeModel[] = [
  {
    id: 'Start',
    offsetY: 50,
    annotations: [{ content: 'Start' }],
    shape: { type: 'Flow', shape: 'Terminator' },
  },
  {
    id: 'Init',
    offsetY: 140,
    annotations: [{ content: 'var i = 0;' }],
    shape: { type: 'Flow', shape: 'Process' },
  },
  {
    id: 'Condition',
    offsetY: 230,
    annotations: [{ content: 'i < 10?' }],
    shape: { type: 'Flow', shape: 'Decision' },
  },
];
let diagram: Diagram = new Diagram({
  width: '100%',
  height: '600px',
  nodes: nodes,
  getNodeDefaults: (node: NodeModel) => {
    node.height = 50;
    node.width = 140;
    node.offsetX = 300;
    node.style = { fill: 'skyblue', strokeColor: 'skyblue' };
    return node;
  },
});
diagram.appendTo('#element');
<!DOCTYPE html>
<html lang="en">

<head>
    <title>EJ2 Diagram</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Typescript UI Controls" />
    <meta name="author" content="Syncfusion" />
    <link href="index.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-buttons/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-popups/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-splitbuttons/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-diagrams/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-navigations/styles/fabric.css" rel="stylesheet" />
    <script src="systemjs.config.js"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>

<body>
    <div id='loader'>Loading....</div>
    <div id='container'>
        <div id='element'></div>
    </div>
</body>

</html>

Connect flow chart nodes

Connect these nodes by adding a connector using the connectors property of diagram and refer the source and target end by using the sourceID and targetID properties.
The required nodes and connectors can be added to form a complete flow diagram.

import { Diagram, NodeModel, ConnectorModel } from '@syncfusion/ej2-diagrams';
let nodes: NodeModel[] = [
  {
    id: 'Start',
    offsetX: 300,
    offsetY: 50,
    annotations: [{ content: 'Start' }],
    shape: { type: 'Flow', shape: 'Terminator' },
    style: { fill: '#d0f0f1', strokeColor: '#797979' },
  },
  {
    id: 'Init',
    offsetX: 300,
    offsetY: 140,
    annotations: [{ content: 'var i = 0;' }],
    shape: { type: 'Flow', shape: 'Process' },
    style: { fill: '#fbfdc5', strokeColor: '#797979' },
  },
  {
    id: 'Condition',
    offsetX: 300,
    offsetY: 230,
    annotations: [{ content: 'i < 10?' }],
    shape: { type: 'Flow', shape: 'Decision' },
    style: { fill: '#c5efaf', strokeColor: '#797979' },
  },
  {
    id: 'Print',
    offsetX: 300,
    offsetY: 320,
    annotations: [{ content: "print('Hello!!');" }],
    shape: { type: 'Flow', shape: 'PreDefinedProcess' },
    style: { fill: '#f8eee5', strokeColor: '#797979' },
  },
  {
    id: 'Increment',
    offsetX: 300,
    offsetY: 410,
    annotations: [{ content: 'i++;' }],
    shape: { type: 'Flow', shape: 'Process' },
    style: { fill: '#fbfdc5', strokeColor: '#797979' },
  },
  {
    id: 'End',
    offsetX: 300,
    offsetY: 500,
    annotations: [{ content: 'End' }],
    shape: { type: 'Flow', shape: 'Terminator' },
    style: { fill: '#d0f0f1', strokeColor: '#797979' },
  },
];
let connector: ConnectorModel[] = [
  { id: 'connector1', sourceID: 'Start', targetID: 'Init' },
  { id: 'connector2', sourceID: 'Init', targetID: 'Condition' },
  {
    id: 'connector3',
    sourceID: 'Condition',
    targetID: 'Print',
    annotations: [{ content: 'Yes' }],
  },
  {
    id: 'connector4',
    sourceID: 'Condition',
    targetID: 'End',
    annotations: [{ content: 'No' }],
    type: 'Orthogonal',
    segments: [
      { type: 'Orthogonal', length: 30, direction: 'Right' },
      { type: 'Orthogonal', length: 300, direction: 'Bottom' },
    ],
  },
  { id: 'connector5', sourceID: 'Print', targetID: 'Increment' },
  {
    id: 'connector6',
    sourceID: 'Increment',
    targetID: 'Condition',
    type: 'Orthogonal',
    segments: [
      { type: 'Orthogonal', length: 30, direction: 'Left' },
      { type: 'Orthogonal', length: 200, direction: 'Top' },
    ],
  },
];
let diagram: Diagram = new Diagram({
  width: '100%',
  height: '600px',
  nodes: nodes,
  connectors: connector,
  getNodeDefaults: (node: NodeModel) => {
    node.height = 50;
    node.width = 140;
    node.offsetX = 300;
    return node;
  },
  getConnectorDefaults: (obj: ConnectorModel): ConnectorModel => {
    obj.type = 'Orthogonal';
    obj.targetDecorator = { shape: 'Arrow', width: 10, height: 10 };
    return obj;
  },
});
diagram.appendTo('#element');
<!DOCTYPE html>
<html lang="en">

<head>
    <title>EJ2 Diagram</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Typescript UI Controls" />
    <meta name="author" content="Syncfusion" />
    <link href="index.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-buttons/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-popups/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-splitbuttons/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-diagrams/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-navigations/styles/fabric.css" rel="stylesheet" />
    <script src="systemjs.config.js"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>

<body>
    <div id='loader'>Loading....</div>
    <div id='container'>
        <div id='element'></div>
    </div>
</body>

</html>

Default values for all nodes and connectors can be set using the getNodeDefaults and getConnectorDefaults properties, respectively. For example, if all nodes have the same width and height, such properties can be moved into getNodeDefaults.

Automatic organization chart

In the ‘Flow Diagram’ section, how to create a diagram manually was discussed. This section explains how to create and position the diagram automatically.

Create Business object (Employee information)

Define Employee Information as JSON data. The following code example shows an employee array whose, Name is used as an unique identifier and ReportingPerson is used to identify the person to whom an employee report to, in the organization.

//Initialize data source...
let data: object[] = [{Name: "Elizabeth", Role: "Director" },
{ Name: "Christina", ReportingPerson: "Elizabeth", Role: "Manager" },
{ Name: "Yoshi", ReportingPerson: "Christina", Role: "Lead" },
{ Name: "Philip", ReportingPerson: "Christina", Role: "Lead" },
{ Name: "Yang", ReportingPerson: "Elizabeth", Role: "Manager" },
{ Name: "Roland", ReportingPerson: "Yang", Role: "Lead" },
{ Name: "Yvonne", ReportingPerson: "Yang", Role: "Lead" }
];

Map data source to diagram

You can configure the above “Employee Information” with diagram, so that the nodes and connectors are automatically generated using the mapping properties. The following code example show how dataSourceSettings is used to map ID and parent with property name identifiers for employee information.

//Initialize data source...

let data: object[] = [{Name: "Elizabeth", Role: "Director" },
{ Name: "Christina", ReportingPerson: "Elizabeth", Role: "Manager" },
{ Name: "Yoshi", ReportingPerson: "Christina", Role: "Lead" },
{ Name: "Philip", ReportingPerson: "Christina", Role: "Lead" },
{ Name: "Yang", ReportingPerson: "Elizabeth", Role: "Manager" },
{ Name: "Roland", ReportingPerson: "Yang", Role: "Lead" },
{ Name: "Yvonne", ReportingPerson: "Yang", Role: "Lead" }
];
let items: DataManager = new DataManager(data as JSON[], new Query().take(7));
//Initialize data source...
let diagram: Diagram = new Diagram({
    width: '100%', height: '600px',
//Configure data source for diagram
    dataSourceSettings: {
        id: 'Name', parentId: 'ReportingPerson', dataManager: items
    }
});

Rendering layout with Datasource

To create an organizational chart, the type of layout should be set as an OrganizationalChart. The following code example shows how DataManager is used to generate Layout based on the DataSourceSettings of the Diagram.

import {
    Diagram,
    ConnectorModel,
    Node,
    DataBinding,
    HierarchicalTree,
    TreeInfo,
    SnapConstraints,
  } from '@syncfusion/ej2-diagrams';
  Diagram.Inject(DataBinding, HierarchicalTree);
  import { DataManager, Query } from '@syncfusion/ej2-data';
  export interface EmployeeInfo {
    Name: string;
    Role: string;
  }
  //To represent the roles
  let codes: object[] = {
    Director: 'rgb(0, 139,139)',
    Manager: 'rgb(30, 30,113)',
    Lead: 'rgb(0, 100,0)',
  };
  // Bind custom data with node
  function getNodeTemplate(node) {
    node.annotations[0].content = (node.data as EmployeeInfo).Name;
    node.style.fill = codes[(node.data as EmployeeInfo).Role];
  }
  let data: object[] = [
    { Name: 'Elizabeth', Role: 'Director' },
    { Name: 'Christina', ReportingPerson: 'Elizabeth', Role: 'Manager' },
    { Name: 'Yoshi', ReportingPerson: 'Christina', Role: 'Lead' },
    { Name: 'Philip', ReportingPerson: 'Christina', Role: 'Lead' },
    { Name: 'Yang', ReportingPerson: 'Elizabeth', Role: 'Manager' },
    { Name: 'Roland', ReportingPerson: 'Yang', Role: 'Lead' },
    { Name: 'Yvonne', ReportingPerson: 'Yang', Role: 'Lead' },
  ];
  let items: DataManager = new DataManager(data as JSON[], new Query().take(7));
  let diagram: Diagram = new Diagram({
    width: '100%',
    height: '600px',
    snapSettings: { constraints: SnapConstraints.None },
    //Use automatic layout to arrange elements on the page
    layout: {
      type: 'OrganizationalChart',
      margin: { left: 10, top: 10 },
      horizontalSpacing: 50,
      verticalSpacing: 50,
      orientation: 'TopToBottom',
      getLayoutInfo: (node: Node, tree: TreeInfo) => {
        if (!tree.hasSubTree) {
          tree.orientation = 'Vertical';
          tree.type = 'Alternate';
        }
      },
    },
    dataSourceSettings: {
      id: 'Name',
      parentId: 'ReportingPerson',
      dataManager: items,
    },
    getNodeDefaults: (obj: Node, diagram: Diagram) => {
      obj.height = 30;
      obj.width = 70;
      obj.shape = { type: 'Basic', shape: 'Rectangle' };
      obj.annotations = [
        { content: (obj.data as EmployeeInfo).Name, style: { color: 'white' } },
      ];
      obj.style.fill = codes[(obj.data as EmployeeInfo).Role];
      return obj;
    },
    getConnectorDefaults: (connector: ConnectorModel, diagram: Diagram) => {
      connector.targetDecorator.shape = 'Arrow';
      connector.cornerRadius = 7;
      connector.type = 'Orthogonal';
      return connector;
    },
  });
  diagram.appendTo('#element');
<!DOCTYPE html>
<html lang="en">

<head>
    <title>EJ2 Diagram</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Typescript UI Controls" />
    <meta name="author" content="Syncfusion" />
    <link href="index.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-buttons/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-popups/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-splitbuttons/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-diagrams/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-navigations/styles/fabric.css" rel="stylesheet" />
    <script src="systemjs.config.js"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>

<body>
    <div id='loader'>Loading....</div>
    <div id='container'>
        <div id='element'></div>
    </div>
</body>

</html>

Customize employee appearance

The following code examples indicate how to define the default appearance of nodes and connectors. The setNodeTemplate is used to update each node based on employee data.

import {
    Diagram,
    ConnectorModel,
    Node,
    DataBinding,
    HierarchicalTree,
    TreeInfo,
    SnapConstraints,
    NodeModel,
    ImageElement,
    TextElement,
    StackPanel,
  } from '@syncfusion/ej2-diagrams';
  Diagram.Inject(DataBinding, HierarchicalTree);
  import { DataManager, Query } from '@syncfusion/ej2-data';
  export interface EmployeeInfo {
    Name: string;
    Role: string;
  }
  //To represent the roles
  let codes: object[] = {
    Director: 'rgb(0, 139,139)',
    Manager: 'rgb(30, 30,113)',
    Lead: 'rgb(0, 100,0)',
  };
  // Bind custom data with node
  function getNodeTemplate(node) {
    node.annotations[0].content = (node.data as EmployeeInfo).Name;
    node.style.fill = codes[(node.data as EmployeeInfo).Role];
  }
  let data: object[] = [
    { Name: 'Elizabeth', Role: 'Director' },
    { Name: 'Christina', ReportingPerson: 'Elizabeth', Role: 'Manager' },
    { Name: 'Yoshi', ReportingPerson: 'Christina', Role: 'Lead' },
    { Name: 'Philip', ReportingPerson: 'Christina', Role: 'Lead' },
    { Name: 'Yang', ReportingPerson: 'Elizabeth', Role: 'Manager' },
    { Name: 'Roland', ReportingPerson: 'Yang', Role: 'Lead' },
    { Name: 'Yvonne', ReportingPerson: 'Yang', Role: 'Lead' },
  ];
  let items: DataManager = new DataManager(data as JSON[], new Query().take(7));
  let diagram: Diagram = new Diagram({
    width: '100%',
    height: '600px',
    snapSettings: { constraints: SnapConstraints.None },
    //Use automatic layout to arrange elements on the page
    layout: {
      type: 'OrganizationalChart',
      margin: { left: 10, top: 10 },
      horizontalSpacing: 50,
      verticalSpacing: 50,
      orientation: 'TopToBottom',
      getLayoutInfo: (node: Node, tree: TreeInfo) => {
        if (!tree.hasSubTree) {
          tree.orientation = 'Vertical';
          tree.type = 'Alternate';
        }
      },
    },
    dataSourceSettings: {
      id: 'Name',
      parentId: 'ReportingPerson',
      dataManager: items,
    },
    getNodeDefaults: (obj: Node, diagram: Diagram) => {
      obj.height = 30;
      obj.width = 70;
      obj.shape = { type: 'Basic', shape: 'Rectangle' };
      obj.annotations = [
        {
          id: 'label1',
          style: {
            fontSize: 11,
            bold: true,
            fontFamily: 'Segoe UI',
            color: 'white',
          },
        },
      ];
      return obj;
    },
    getConnectorDefaults: (connector: ConnectorModel, diagram: Diagram) => {
      connector.targetDecorator.shape = 'Arrow';
      connector.type = 'Orthogonal';
      return connector;
    },
    setNodeTemplate: (node: NodeModel) => {
      let codes: Object = {
        Director: 'rgb(0, 139,139)',
        Manager: 'rgb(30, 30,113)',
        Lead: 'rgb(0, 100,0)',
      };
      let content = new StackPanel();
      content.id = node.id + '_outerstack';
      content.orientation = 'Horizontal';
      content.style.strokeColor = 'gray';
      content.style.fill = (codes as any)[
        (node.data as EmployeeInfo).Role
      ] as string;
      content.padding = { left: 5, right: 5, top: 5, bottom: 5 };
      let innerContent = new ImageElement();
      innerContent.style.strokeColor = 'blue';
      innerContent.id = node.id + '_innerstack';
      innerContent.style.fill = 'skyblue';
      innerContent.width = 50;
      innerContent.height = 50;
      let text = new TextElement();
      text.id = node.id + '_text';
      text.content = (node.data as EmployeeInfo).Name;
      text.margin = { left: 15, right: 5, top: 5, bottom: 5 };
      text.style.color = 'black';
      content.children = [innerContent, text];
      return content;
    },
  });
  diagram.appendTo('#element');
<!DOCTYPE html>
<html lang="en">

<head>
    <title>EJ2 Diagram</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Typescript UI Controls" />
    <meta name="author" content="Syncfusion" />
    <link href="index.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-buttons/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-popups/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-splitbuttons/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-diagrams/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-navigations/styles/fabric.css" rel="stylesheet" />
    <script src="systemjs.config.js"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>

<body>
    <div id='loader'>Loading....</div>
    <div id='container'>
        <div id='element'></div>
    </div>
</body>

</html>

NOTE

You can refer to our JavaScript Diagram feature tour page for its groundbreaking feature representations. You can also explore our JavaScript Diagram example to knows how to present and manipulate data.