gojs
Version:
Interactive diagrams, charts, and graphs, such as trees, flowcharts, orgcharts, UML, BPMN, or business diagrams
404 lines (354 loc) • 17.5 kB
HTML
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>GoJS and Angular -- Northwoods Software</title>
<!-- Copyright 1998-2020 by Northwoods Software Corporation. -->
<script src="goIntro.js"></script>
</head>
<body onload="goIntro()">
<div id="container" class="container-fluid">
<div id="content">
<h1>Using GoJS with Angular</h1>
<p class="box" style="background-color: lightgoldenrodyellow;">
Examples of most of the topics discussed on this page can be found in the <a href="https://github.com/NorthwoodsSoftware/gojs-angular-basic"
target="_blank">gojs-angular-basic</a>
project,
which serves as a simple starter project.
</p>
<p>
If you are new to GoJS, it may be helpful to first visit the <a href="../learn/index.html" target="_blank">Getting
Started Tutorial</a>.
</p>
<p>
The easiest way to get a component set up for a GoJS Diagram is to use the <a href="#TODO" target="_blank">gojs-angular</a>
package,
which exports Angular Components for GoJS Diagrams, Palettes, and Overviews.
More information about the package, including the various props it takes, can be found on the
<a href="https://npmjs.com/gojs-react" target="_blank">NPM</a> page. Our examples will be using a <a>GraphLinksModel</a>,
but any model can be used.
</p>
<p>
You can see a sample project using all GoJS / Angular Components <a href="https://github.com/NorthwoodsSoftware/gojs-angular-basic">here</a>.
</p>
<h2 id="GeneralInformation">General Information</h2>
<h3 id="Installation">Installation</h3>
<p>
To use the published components, make sure you install GoJS and gojs-angular: <code>npm install gojs gojs-angular</code>.
</p>
<h3 id="AboutComponentStyling">About Component Styling</h3>
<p>
Whether you are using the published Diagram, Palette, or Overview Angular / GoJS Components, you will probably
want to style them.
First, you'll need to style a CSS class for the div of your GoJS Diagram / Palette / Overview such as:
</p>
<pre class="lang-css">
/* app.component.css */
.myDiagramDiv {
background: whitesmoke;
width: 800px;
height: 300px;
border: 1px solid black;
}
</pre>
<p> To style the GoJS Diagram / Palette / Overivew div, which will reside in the Angular / GoJS
Component(s) you are using, make sure you set <code>encapsulation: ViewEncapsulation.None</code> in the <code>@Component</code>
decorator
of the component holding your Angular / GoJS Component(s). Without this, your styling will not effect the
component divs.
Read more about Angular view encapsulation <a href="https://angular.io/api/core/ViewEncapsulation">here</a>.
</p>
<p>Your <code>@Component</code> decorator for the component holding the your GoJS / Angular Component(s) should
look something
like: </p>
<pre class="lang-ts">
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
encapsulation: ViewEncapsulation.None
})
</pre>
<h3 id="DataSyncService">The DataSyncService</h3>
<p>
The <code>gojs-angular</code> package comes with an Angular <a href="https://angular.io/tutorial/toh-pt4">service</a>
called DataSyncService (demonstrated later), which is used to
easily merge changes (a <a href="https://gojs.net/latest/api/symbols/IncrementalData.html">go.IncrementalData</a>
instance). </p>
<p>This service has three static functions: </p>
<ul>
<li><code>syncNodeData(changes, array)</code> - Merges any node data changes in a go.IncrementalData object
with a given array of node data, then returns the new array</li>
<li><code>syncLinkData(changes, array)</code> - Merges any link data changes in a go.IncrementalData object
with a given array of link data, then returns the new array. <strong>Note</strong>: Ensure you set the <a
href="https://gojs.net/latest/api/symbols/GraphLinksModel.html#linkKeyProperty">linkKeyProperty</a>
if you are using GraphLinksModel, so data merging is possible.</li>
<li><code>syncModelData(changes, object)</code> - Merges any modelData changes in a go.IncrementalData object
with a given modelData object, then returns the new object</li>
</ul>
<p>These functions should allow you to keep your data synced up as needed, without needing to write lots of
code.</p>
<h3 id="ListeningForModelChanges">Listening for Model Changes</h3>
<p>
It is common practice to want to listen for when data changes in a Diagram or Palette, then do something with
those changes on an application-level (such as data syncing). That's why, for both the DiagramComponent and
PaletteComponent, there is a <code>modelChange</code> @Input property function (more info below).
</p>
<p>
Note that the UndoManager should always be enabled to allow for transactions to take place, but the
UndoManager.maxHistoryLength can be set to 0 to prevent undo and redo.
</p>
<br>
<h2 id="UsingDiagramComponent">Using the Diagram Component</h2>
<p>
Diagram Component accepts several <code>@Input()</code> Angular properties, some of which
are
optional. They are:
<ul>
<li><code>initDiagram</code> - A function that must return a GoJS Diagram. You may define your Diagram's
Node
and Link templates here.</li>
<li><code>divClassName</code> - A class name for your Diagram div</li>
<li><code>nodeDataArray</code> - An array containing data objects for your nodes </li>
<li><code>linkDataArray</code> - An array containing data objects for your links </li>
<li><code>modelData</code> - A data object,
containing your diagram's <a href="https://gojs.net/latest/api/symbols/Model.html#modelData">model.modelData</a>.
This property is optional.
<li><code>skipsDiagramUpdate</code> - A boolean flag, specifying whether the component should skip updating,
often set when updating state from a GoJS model change.</li>
<li><code>modelChange</code> - A function, which accepts a <a href="">go.IncrementalData</a> object.
This function will fire when your Diagram's model changes, allowing you to decide what to do with those
changes. A common practice is to sync your app-level data to reflect the changes in the diagram model,
which
is made simple using the DataSyncService <code>gojs-angular</code> ships with. </li>
</ul>
</p>
<p>For example, these properties may look something like this: </p>
<pre class="lang-ts">
public initDiagram(): go.Diagram {
const $ = go.GraphObject.make;
const dia = $(go.Diagram, {
'undoManager.isEnabled': true, // must be set to allow for model change listening
// 'undoManager.maxHistoryLength': 0, // uncomment disable undo/redo functionality
model: $(go.GraphLinksModel,
{
linkKeyProperty: 'key' // IMPORTANT! must be defined for merges and data sync when using GraphLinksModel
}
)
});
// define the Node template
dia.nodeTemplate =
$(go.Node, 'Auto',
{
toLinkable: true, fromLinkable: true
},
$(go.Shape, 'RoundedRectangle', { stroke: null },
new go.Binding('fill', 'color')
),
$(go.TextBlock, { margin: 8 },
new go.Binding('text', 'key'))
);
return dia;
}
public diagramNodeData: Array<go.ObjectData> = [
{ key: 'Alpha', color: 'lightblue' },
{ key: 'Beta', color: 'orange' },
{ key: 'Gamma', color: 'lightgreen' },
{ key: 'Delta', color: 'pink' }
];
public diagramLinkData: Array<go.ObjectData> = [
{ key: -1, from: 'Alpha', to: 'Beta' },
{ key: -2, from: 'Alpha', to: 'Gamma' },
{ key: -3, from: 'Beta', to: 'Beta' },
{ key: -4, from: 'Gamma', to: 'Delta' },
{ key: -5, from: 'Delta', to: 'Alpha' }
];
public diagramDivClassName: string = 'myDiagramDiv';
public diagramModelData = { prop: 'value' };
public skipsDiagramUpdate = false;
// When the diagram model changes, update app data to reflect those changes
public diagramModelChange = function(changes: go.IncrementalData) {
// when setting state here, be sure to set skipsDiagramUpdate: true since GoJS already has this update
// (since this is a GoJS model changed listener event function)
// this way, we don't log an unneeded transaction in the Diagram's undoManager history
this.skipsDiagramUpdate = true;
this.diagramNodeData = DataSyncService.syncNodeData(changes, this.diagramNodeData);
this.diagramLinkData = DataSyncService.syncLinkData(changes, this.diagramLinkData);
this.diagramModelData = DataSyncService.syncModelData(changes, this.diagramModelData);
};
</pre>
<p>
Once you've defined your <code>@Input</code> properties for your DiagramComponent, pass these properties
to your DiagramComponent in your template, like so:
</p>
<pre class="lang-html">
<gojs-diagram
[initDiagram]='initDiagram'
[nodeDataArray]='diagramNodeData'
[linkDataArray]='diagramLinkData'
[modelData]='diagramModelData'
[skipsDiagramUpdate]='skipsDiagramUpdate'
(modelChange)='diagramModelChange($event)'
[divClassName]='diagramDivClassName'>
</gojs-diagram>
</pre>
<p>
You will now have a GoJS Diagram working in your Angular application.
</p>
<br>
<h2 id="UsingPaletteComponent">Using the Palette Component</h2>
The Palette Component accepts the following Angular <code>@Input()</code> properties.
<ul>
<li><code>initPalette</code> - A function that must return a GoJS Palette. You may define your Palette's Node
and Link templates here.</li>
<li><code>divClassName</code> - A class name for the div your Palette div</li>
<li><code>nodeDataArray</code> - An array containing data objects for your nodes </li>
<li><code>linkDataArray</code> - An array containing data objects for your links </li>
<li><code>modelData</code> - A data object,
containing your palette's <a href="https://gojs.net/latest/api/symbols/Model.html#modelData">model.modelData</a>.
This property is optional.
<li><code>modelChange</code> - A function, which accepts a <a href="">go.IncrementalData</a> object.
This function will fire when your Palette's model changes, allowing you to decide what to do with those
changes. A common practice is to sync your app-level data to reflect the changes in the palette model,
which
is made simple using the DataSyncService <code>gojs-angular</code> ships with. </li>
</ul>
<p>
Define these properties in your component that will hold that Palette Component, such as:
</p>
<pre class="lang-ts">
public initPalette(): go.Palette {
const $ = go.GraphObject.make;
const palette = $(go.Palette);
// define the Node template
palette.nodeTemplate =
$(go.Node, 'Auto',
$(go.Shape, 'RoundedRectangle',
{
stroke: null
},
new go.Binding('fill', 'color')
),
$(go.TextBlock, { margin: 8 },
new go.Binding('text', 'key'))
);
palette.model = $(go.GraphLinksModel,
{
linkKeyProperty: 'key' // IMPORTANT! must be defined for merges and data sync when using GraphLinksModel
});
return palette;
}
public paletteNodeData: Array<go.ObjectData> = [
{ key: 'PaletteNode1', color: 'firebrick' },
{ key: 'PaletteNode2', color: 'blueviolet' }
];
public paletteLinkData: Array<go.ObjectData> = [
{ from: 'PaletteNode1', to: 'PaletteNode2' }
];
public paletteModelData = { prop: 'val' };
public paletteDivClassName = 'myPaletteDiv';
public paletteModelChange = function(changes: go.IncrementalData) {
this.paletteNodeData = DataSyncService.syncNodeData(changes, this.paletteNodeData);
this.paletteLinkData = DataSyncService.syncLinkData(changes, this.paletteLinkData);
this.paletteModelData = DataSyncService.syncModelData(changes, this.paletteModelData);
};
</pre>
<p>
Then pass these properties to your Palette Component in your template, like:
</p>
<pre class="lang-html">
<gojs-palette
[initPalette]='initPalette'
[nodeDataArray]='paletteNodeData'
[linkDataArray]='paletteLinkData'
[modelData]='paletteModelData'
(modelChange)='paletteModelChange($event)'
[divClassName]='paletteDivClassName'>
</gojs-palette></pre>
<p>
You should now have a GoJS Palette Component working in your Angular application.
</p>
<br>
<h2 id="UsingOverviewComponent">Using the Overview Component</h2>
<p>
The Overview Component accepts the following Angular <code>@Input()</code> properties.
</p>
<ul>
<li><code>initOverview</code> - A function that must return a GoJS Overview.</li>
<li><code>divClassName</code> - A class name for your Overview div</li>
<li><code>observedDiagram</code> - The GoJS Diagram this Overview observes</li>
</ul>
<p>
Define these properties in the component that will hold your Overview Component, like:
</p>
<pre class="lang-ts">
public oDivClassName = 'myOverviewDiv';
public initOverview(): go.Overview {
const $ = go.GraphObject.make;
const overview = $(go.Overview);
return overview;
}
public observedDiagram = null;</pre>
<p>
Then pass these properties to your Overview Component in your template, like:
</p>
<pre class="lang-html">
<gojs-overview
[initOverview]='initOverview'
[divClassName]='oDivClassName'
[observedDiagram]='observedDiagram'>
</gojs-overview></pre>
<p>
But, we're not done yet. <code>observedDiagram</code> is null, so the Overview will observe anything.
To assign your Overview a Diagram to observe, you will have to reassign the <code>observedDiagram</code>
property after initialization. To do so,
reassign the bound <code>observedDiagram</code> property in your component holding your Overview
Component in the <code>ngAfterViewInit</code> lifecycle hook.
</p>
<p>
<strong>Note</strong>: To avoid a <code>ExpressionChangedAfterItHasBeenCheckedError</code>, you must inform
Angular
to then detect changes.
This can be done with the <a href="https://angular.io/api/core/ChangeDetectorRef">ChangeDetectorRef</a>.detectChanges()
method. You can inject a ChangeDetectorRef instance
into your wrapper Component constructor, and use that after you alter <code>observedDiagram</code> to call
detectChanges(). Like so:
</p>
<pre class="lang-ts">
constructor(private cdr: ChangeDetectorRef) { }
public ngAfterViewInit() {
if (this.observedDiagram) return;
// in this snippet, this.myDiagramComponent is a reference to a GoJS/Angular Diagram Component
// that has a valid GoJS Diagram
this.observedDiagram = this.myDiagramComponent.diagram;
// IMPORTANT: without this, Angular will throw ExpressionChangedAfterItHasBeenCheckedError (dev mode only)
this.cdr.detectChanges();
}
</pre>
<p>
Now, after initialization, your Overview should display appropriately.
</p>
<br>
<h2 id="UpdatingPropertiesBasedOnAppState">Updating Properties Based on App State</h2>
<p>You may have some app-level properties you want to effect the behavior / appearance of your Diagram, Palette,
or Overview. You could subclass their respective components and add <code>@Input</code> bindings with specific
setter methods, or, more simply, you can have an <code>ngOnChanges</code> function in your app-level component
that updates various Diagram / Palette / Component properties based on your app state.</p>
<p>For example, say you have an app-level property called <code>showGrid</code>. When <code>showGrid</code> is
true, your Diagram's grid should be visible -- when false, it should be invisible. In your AppComponent, you
could do something like: </p>
<pre class="lang-ts">
// myDiagramComponent is a reference to your DiagramComponent
@ViewChild('myDiagram', { static: true }) public myDiagramComponent: DiagramComponent;
public ngDoCheck() {
// whenever showGrid changes, update the diagram.grid.visible in the child DiagramComponent
if (this.myDiagramComponent && this.myDiagramComponent.diagram instanceof go.Diagram) {
this.myDiagramComponent.diagram.grid.visible = this.showGrid;
}
}
</pre>
</div>
</div>
</body>
</html>