Serialization in Angular Diagram component

10 Dec 202416 minutes to read

Serialization is the process of converting the state of the diagram into a format that can be saved and later restored. This ensures that the diagram’s current state, including its nodes, connectors, and configurations, can be persisted across sessions.

Serialization involves saving the diagram’s state as a JSON string, which can then be stored in a database, file, or other storage medium. When needed, the serialized string can be deserialized to recreate the diagram in its previous state.

To save and load the diagram in Angular, refer to the below video link.

Save

The diagram method saveDiagram, helps to serialize the diagram as a string. This method captures the entire diagram’s configuration and content, converting it into a string representation.

The following code illustrates how to save the diagram:

//returns serialized string of the Diagram
saveData = this.diagram.saveDiagram();

This JSON string can be stored in local storage for future use. The following code illustrates how to save the serialized string into local storage and how to retrieve it:

//Saves the string in to local storage
localStorage.setItem('fileName', saveData);

// Retrieve the saved string from local storage
saveData = localStorage.getItem('fileName');

The diagram can also be saved as raster or vector image files. For more information about saving the diagram as images, refer to the Print and Export section.

Load

The diagram can be loaded from serialized string data using the loadDiagram method. The saved string should be passed as the parameter of the loadDiagram method. The following code illustrates how to load the diagram from serialized string data:

/*
 * Loads the diagram from saved JSON data.
 * parameter 1 - The string representing the diagram model JSON to be loaded.
 * parameter 2 - Whether it is ej1 data or not (optional)
 */
this.diagram.loadDiagram(saveData);

NOTE

Before loading a new diagram, existing diagram is cleared.

Loaded Event

The loaded event triggers when all diagram elements are loaded using loadDiagram method. You can use this event to customize diagram elements during the loading process.

<ejs-diagram #diagram id="diagram" width="100%" height="700px" (loaded)="loaded()" >
</ejs-diagram>
export class AppComponent {
  public loaded(args:ILoadedEventArgs): void {
      //You can use this event to customize diagram elements during the loading process
  }
}

The event has two arguments such as name, diagram

name

Type: String

Description: Returns the event name.

diagram

Type: Diagram

Description: Returns the diagram model properties.

Users can perform customizations or modifications to the diagram elements once the loading process is complete.

Prevent default values

The preventDefaults property of serializationSettings is used to simplify the saved JSON object by excluding default properties that are inherent to the diagram. This helps reduce the size of the serialized data and improves efficiency when saving and loading diagrams.

By enabling preventDefaults, only properties that you set in diagram are included in the serialized JSON object. This optimization is useful for scenarios where minimizing data size is crucial, such as in applications with large diagrams or when optimizing network transfers.

The following code illustrates how to enable the preventDefaults property to simplify the JSON object:

<ejs-diagram #diagram id="diagram" width="100%" height="700px" (serializationSettings)="serializationSettings" >
</ejs-diagram>
export class AppComponent {
  public serializationSettings: SerializationSettingsModel = {};
  
  ngOnInit() {
    this.serializationSettings = { preventDefaults: true };
  }
}

Save and load diagram using uploader control

The JSON files can be uploaded using the uploader component, where they are parsed to extract the JSON data they contain. To achieve this, configure the uploader component with the saveUrl property to receive uploaded files and store them on the server. Similarly, use the removeUrl property to handle file removal operations on the server.

When a JSON file is uploaded, it undergoes parsing to extract its JSON data. This data is then loaded into the diagram using the loadDiagram method.

import { ViewChild, Component, ViewEncapsulation  } from '@angular/core';
import { DiagramComponent, DiagramModule } from '@syncfusion/ej2-angular-diagrams';
import { Uploader, FileInfo } from '@syncfusion/ej2-inputs';
import { NodeModel } from '@syncfusion/ej2-diagrams';

@Component({
  imports: [DiagramModule],

  providers: [],
  standalone: true,
  selector: 'app-container',
  template: ` <div> <input id="fileupload" type="file" />
  <button (click)="onSaveClick()">Save Diagram</button> </div>
  <ejs-diagram #diagram id="diagram" width="100%" height="600px" [nodes]="nodes" > </ejs-diagram>`,
  encapsulation: ViewEncapsulation.None,
})
export class AppComponent {
  @ViewChild("diagram")
  public diagram!: DiagramComponent;
  public uploadObject: Uploader;
  public nodes: NodeModel[] = [];
  constructor() {
    this.uploadObject = new Uploader({
      asyncSettings: {
        saveUrl:
          'https://services.syncfusion.com/js/production/api/FileUploader/Save',
        removeUrl:
          'https://services.syncfusion.com/js/production/api/FileUploader/Remove',
      },
      success: this.onUploadSuccess.bind(this),
    });
  }
  ngOnInit() {
    // Initialize nodes
    this.nodes = [
    {
      id: 'Start',
      width: 140,
      height: 50,
      offsetX: 300,
      offsetY: 50,
      annotations: [{ id: 'label1', content: 'Start' }],
      shape: { type: 'Flow', shape: 'Terminator' },
    },
  ];
}

  ngAfterViewInit() {
    this.uploadObject.appendTo('#fileupload');
  }

  onUploadSuccess(args: { file: FileInfo }) {
    const file: any = args.file.rawFile;
    const reader = new FileReader();
    reader.readAsText(file);
    reader.onloadend = this.loadDiagram.bind(this);
  }

  loadDiagram(event: ProgressEvent<FileReader>) {
    const jsonString = event.target?.result as string;
    this.diagram.loadDiagram(jsonString);
  }

  download(data: string): void {
    if ((window.navigator as any).msSaveBlob) {
      const blob: any = new Blob([data], {
        type: 'data:text/json;charset=utf-8,',
      });
      (window.navigator as any).msSaveBlob(blob, 'Diagram.json');
    } else {
      const dataStr: string =
        'data:text/json;charset=utf-8,' + encodeURIComponent(data);
      const a: HTMLAnchorElement = document.createElement('a');
      a.href = dataStr;
      a.download = 'Diagram.json';
      document.body.appendChild(a);
      a.click();
      a.remove();
    }
  }

  onSaveClick() {
    this.download(this.diagram.saveDiagram());
  }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

Importing and Exporting Mind Map and Flowchart Diagrams using Mermaid Syntax

The Diagram supports saving diagrams in Mermaid syntax format. Mermaid is a Markdown-inspired syntax that automatically generates diagrams. With this functionality, you can easily create mind maps and flowcharts from Mermaid syntax data, simplifying the visualization of complex ideas and processes without manual drawing. Additionally, you can export your mind maps and flowcharts to Mermaid syntax, allowing for easy sharing, editing, and use across different platforms.

Save diagram as Mermaid syntax

The saveDiagramAsMermaid method serializes the diagram into a Mermaid-compatible string format. This method is specifically designed for diagrams that utilize Flowchart and Mind map layouts. The following code illustrates how to save the diagram in Mermaid string format.

//returns the serialized Mermaid string of the Diagram
data = this.diagram.saveDiagramAsMermaid();

Load diagram from Mermaid syntax

You can load a diagram from the serialized Mermaid syntax data using the loadDiagramFromMermaid method. The following code illustrates how to load a diagram from a Mermaid string data.

Load flowchart layout

The following example shows how to load flowchart diagram from mermaid syntax.

import { Component, ViewChild, ViewEncapsulation } from '@angular/core';
import { DiagramComponent, DiagramModule } from '@syncfusion/ej2-angular-diagrams';
import { Diagram, NodeModel, ConnectorModel, FlowShapeModel, FlowchartLayout } from '@syncfusion/ej2-diagrams';

Diagram.Inject(FlowchartLayout);

@Component({
  imports: [
    DiagramModule
  ],

  providers: [],
  standalone: true,
  selector: "app-container",
  template: `
  <button (click)="loadMermaidFlowchart()">Load</button>
  <ejs-diagram #diagram id="diagram" width="100%" height="600px" [getNodeDefaults]="getNodeDefaults"
  [getConnectorDefaults]="getConnectorDefaults" [layout]="layout"> </ejs-diagram>`,
  encapsulation: ViewEncapsulation.None
})

export class AppComponent {
  @ViewChild("diagram")
  public diagram!: DiagramComponent;

  public getNodeDefaults(node: NodeModel): NodeModel {
    node.width = 120;
    node.height = 50;
    if ((node.shape as FlowShapeModel).shape === 'Decision') {
      node.height = 80;
    }

    return node;
  }

  public getConnectorDefaults(connector: ConnectorModel): ConnectorModel {
    connector.type = 'Orthogonal';
    return connector;
  }

  public layout = { type: 'Flowchart' }

  public loadMermaidFlowchart() {
    const mermaidFlowchartData = `flowchart TD
        A[Start] --> B(Process)
        B -.- C{Decision}
        C --Yes--> D[Plan 1]
        C ==>|No| E[Plan 2]
        style A fill:#90EE90,stroke:#333,stroke-width:2px;
        style B fill:#4682B4,stroke:#333,stroke-width:2px;
        style C fill:#FFD700,stroke:#333,stroke-width:2px;
        style D fill:#FF6347,stroke:#333,stroke-width:2px;
        style E fill:#FF6347,stroke:#333,stroke-width:2px;`;

    // load the mermaid flowchart data to diagram
    //parameter: mermaidFlowchartData - mermaid format string data for flowchart
    this.diagram.loadDiagramFromMermaid(mermaidFlowchartData);
  }

}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

Load mindmap layout

The following example shows how to load mind map diagram from mermaid syntax.

import { Component, ViewChild, ViewEncapsulation } from '@angular/core';
import { DiagramComponent, DiagramModule } from '@syncfusion/ej2-angular-diagrams';
import { Diagram, NodeModel, ConnectorModel, TextStyleModel, ShapeAnnotationModel,
  DecoratorModel, StrokeStyleModel, MindMap } from '@syncfusion/ej2-diagrams';

Diagram.Inject(MindMap);

@Component({
  imports: [
    DiagramModule
  ],

  providers: [],
  standalone: true,
  selector: "app-container",
  template: `
  <button (click)="loadMermaidMindmap()">Load</button>
  <ejs-diagram #diagram id="diagram" width="100%" height="600px" [getNodeDefaults]="getNodeDefaults"
  [getConnectorDefaults]="getConnectorDefaults" [layout]="layout"> </ejs-diagram>`,
  encapsulation: ViewEncapsulation.None
})

export class AppComponent {
  @ViewChild("diagram")
  public diagram!: DiagramComponent;

  public getNodeDefaults(node: NodeModel): NodeModel {
    node.width = 120;
    node.height = 50;
    return node;
  }

  public getConnectorDefaults(connector: ConnectorModel): ConnectorModel {
    connector.type = 'Orthogonal';
    (connector.targetDecorator as DecoratorModel).shape = 'None';
    return connector;
  }

  public layout = {
    type: 'MindMap',
    verticalSpacing: 50,
    horizontalSpacing: 50,
    orientation: 'Horizontal',
  }

  public loadMermaidMindmap() {
    const mermaidMindmapData = `mindmap
                            root((mindmap))
                              Origins
                                Popularisation
                              Research
                                On effectivness<br/>and features
                                On Automatic creation
                              Tools
                                Pen and paper
                                Mermaid `;

    // load the mermaid mindmap data to diagram
    //parameter: mermaidMindmapData - mermaid format string data for mindmap
    this.diagram.loadDiagramFromMermaid(mermaidMindmapData);
  }

}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

NOTE

Mermaid syntax data serialization and deserialization are only supported for Flowchart and Mind map layouts. Please ensure that your diagram uses one of these layouts to successfully load the data.