Skip to content

Save Persistence Example

This example demonstrates how to implement save and restore functionality for the diagram in ngDiagram using Angular features.

import '@angular/compiler';
import { Component, inject, Injector } from '@angular/core';
import {
initializeModel,
NgDiagramBackgroundComponent,
NgDiagramComponent,
NgDiagramModelService,
provideNgDiagram,
type Model,
type NgDiagramConfig,
} from 'ng-diagram';
import { NavBarComponent } from './nav-bar/nav-bar.component';
import { SaveStateService } from './save.service';
@Component({
imports: [NgDiagramComponent, NgDiagramBackgroundComponent, NavBarComponent],
template: `
<nav-bar (loadModel)="loadModel($event)"></nav-bar>
<div class="not-content diagram">
<ng-diagram [model]="model" [config]="config">
<ng-diagram-background />
</ng-diagram>
</div>
`,
styleUrl: './diagram.component.scss',
providers: [NgDiagramModelService, SaveStateService, provideNgDiagram()],
})
export class DiagramComponent {
private injector = inject(Injector);
config = {
zoom: {
max: 3,
zoomToFit: {
onInit: true,
padding: 155,
},
},
} satisfies NgDiagramConfig;
model = initializeModel({
nodes: [
{
id: '1',
position: { x: 0, y: 0 },
data: {},
},
{
id: '2',
position: { x: 100, y: 50 },
data: {},
},
{
id: '3',
position: { x: 200, y: 100 },
data: {},
},
],
});
loadModel(model: Partial<Model>): void {
this.model = initializeModel(model, this.injector);
}
}
  • Persistence: Saves the diagram state to local storage.
  • Restoration: Loads the saved state back into the diagram.
  • Clear: Removes the saved state from local storage.
  • Save Persistence Service:
    The SaveStateService manages saving, loading, and clearing the diagram state using Angular signals and effects.

  • NavBar Component:
    The navigation bar provides buttons for saving, loading, and clearing the diagram state. Button states are reactive.

  • Save: Serializes and stores the current diagram state.
  • Load: Restores the diagram from the saved state.
  • Clear: Removes the saved state from local storage.