Skip to content

Latest commit

 

History

History
184 lines (138 loc) · 17.9 KB

README.md

File metadata and controls

184 lines (138 loc) · 17.9 KB

Angular OrgChart

English | 简体中文 | 繁體中文

Angular 22 standalone library and interactive examples based on the MIT-licensed OrgChart v8 behavior. The interaction engine is part of this package, not an orgchart npm dependency. The public Angular API uses signal inputs, live TemplateRef views, outputs, and automatic teardown. This is a new major version, not a drop-in replacement for the Angular 8 NgModule API.

Quick start · Angular bindings · Data · Options · Methods · Events and export · Demos · Publishing

Quick start

In an Angular application with @angular/core and @angular/common matching ^22.3.0, install npm install @dabeng/angular-orgchart. Import the standalone component directly; no NgModule, jQuery, or additional stylesheet is required.

import { Component, viewChild } from '@angular/core';
import { OrgChartComponent, type ChartOptions } from '@dabeng/angular-orgchart';

@Component({
	selector: 'team-chart', imports: [OrgChartComponent],
	template: `<angular-orgchart [data]="team" [options]="options" />`
})
export class TeamChart {
	readonly team = { id: 'ops', name: 'Operations', children: [{ id: 'lead', name: 'Alex', role: 'Lead' }] };
	readonly options: ChartOptions = { nodeContent: 'role', zoom: true, minimap: true };
	readonly chart = viewChild.required(OrgChartComponent);
	snapshot() { return this.chart().api()?.getHierarchy(true); }
}

Angular bindings

Binding Contract
[data] A ChartSource; takes precedence over options.data. Pass a new reference to load new data. Chart edits do not mutate your input records.
[options] A ChartOptions patch. Replace the object and set explicit values (e.g. zoom: false); omitting a previous key does not reset it.
[nodeTemplate] An Angular TemplateRef<NodeContext>; let-node receives the ChartNode. Bindings stay live. Takes precedence over options.nodeTemplate.
(ready) Emits the ChartApi after the browser view initializes. api() on a component reference returns the same instance, or null before initialization.
(nodeClick) Emits the clicked node's data, not a MouseEvent or DOM element.
<ng-template #person let-node><strong>{{ node.name }}</strong></ng-template>
<angular-orgchart [data]="team" [nodeTemplate]="person" />

The host stays empty during server rendering. Angular destroys the engine, listeners and embedded views when the component is removed. Prefer Angular templates for application data; the string-returning options.nodeTemplate inserts trusted HTML only.

Data

ChartNode is a record with application-defined fields. Put layout flags on the node; put the field names used to read labels and IDs in options. ChartSource accepts four shapes:

Source Shape and interpretation
Nested tree One root object. Its children array holds its direct reports; omit it at leaves. See team above.
Flat rows An array of records with parent_id; the root omits this field or sets it to null. Order is arbitrary; siblings retain input order. For example, [{ id: 2, parent_id: 0, name: 'Alex' }, { id: 0, name: 'Ops' }] has root 0.
Grouped family An array of groups, each containing one or more people. Put descendant groups in the appropriate member's children, e.g. [[{ id: 'a', name: 'Alex' }, { id: 'b', name: 'Sam', children: [[{ id: 'c', name: 'Lee' }]] }]]. Family example.
HTML list Pass a browser HTMLUListElement, not an HTML string or selector. The first root li supplies the label and data-* fields; nested ul elements supply children. List example.

Nonempty flat input must have exactly one root. The nodeId field must contain a nonempty string or finite number. 0 is valid; 1 and '1' identify the same node. Missing or duplicate IDs, missing parents, multiple roots and cycles are errors. An empty array renders no nodes.

Node field Effect
id, name, custom fields By default id identifies the DOM node and name supplies the title. Give every node a unique ID to export its hierarchy. Fields such as role are available in templates and callbacks.
collapsed, className collapsed: true initially hides this node's children. className adds CSS classes to this node, not to the whole chart.
hybrid, compact hybrid: true lays out descendants vertically; compact: true packs a branch into a compact group. Vertical layout takes precedence.
outsider Marks an outside member in a family group; grouping and descendants still come from the array structure.

Options

Pass a ChartOptions object to [options] or api.setOptions(). A dash means no value is configured by default. See the TypeScript signatures for callback types.

Option Default What it controls
data — A ChartSource. Use this or the higher-priority [data] input.
nodeTitle, nodeContent, nodeId 'name', —, 'id' Field names, not literal labels. Set nodeContent: 'role' for a second line. The default renderer treats both labels as text.
nodeTemplate, createNode — nodeTemplate(data) returns trusted HTML; it does not compile Angular bindings. createNode(element, data) runs per rendered node, after Angular template content is attached when used. Do not expect hover controls to exist yet.
initCompleted — (chart: HTMLElement) => void after the rendered chart is attached; unlike (ready), it receives the DOM element, not the API.
direction 't2b' Top to bottom; alternatives: 'b2t' bottom to top, 'l2r' left to right, 'r2l' right to left. Other values throw RangeError.
visibleLevel 999 Initially expanded depth, root = level 1. true restores 999, false shows only level 1, 0 hides all nodes. Other numeric values must be nonnegative integers.
verticalLevel, compact — Start vertical layout at a level (e.g. 3); use compact: true for all branches or (data) => boolean to select branches. Node-level compact flags still apply.
toggleSiblingsResp false When enabled, left and right controls toggle siblings on their own side independently.
pan, zoom, minimap all false Drag the background to pan; use the wheel or pinch to zoom. Drag the minimap viewport to navigate. Its wheel works even if main-chart zoom is off.
zoomoutLimit, zoominLimit 0.5, 7 Inclusive min/max scale. Both must be positive and finite, minimum ≤ maximum, otherwise RangeError.
draggable, drag, dropCriteria false, alias, — Enable node reparenting. drag is an alias; draggable wins in the same patch. dropCriteria(draggedNode, oldParent, candidate) receives DOM elements (oldParent may be null); return false to exclude a target.
chartClass, icons '', built-in oci classes Add classes to .orgchart; override individual icon class names without replacing the rest. Keys: theme, parentNode, expandToUp, collapseToDown, collapseToLeft, expandToRight, backToCompact, backToLoose, collapsed, expanded, spinner.
exportButton, exportButtonName false, 'Export' Show the built-in download button next to the chart; change its label. An application button can call api.export() instead.
exportFilename, exportFileextension, exportScale 'OrgChart', 'png', 2 Base filename, 'png' or 'pdf', and canvas resolution multiplier. Nonpositive scale falls back to 1; increasing scale adds detail without enlarging the logical PDF page.

Methods

Get the ChartApi from (ready) or chart().api() as in the example. chartContainer is the host, chart the rendered .orgchart (nullable), and options the current read-only settings. Methods taking node expect a rendered .node HTMLElement, not a record, ID or selector. Here is an edit followed by a snapshot suitable for persistence:

import type { ChartApi } from '@dabeng/angular-orgchart';

function addAnalyst(api: ChartApi) {
	const parent = api.chart?.querySelector<HTMLElement>('#ops');
	if (!parent) return;
	api.addChildren(parent, [{ id: 'analyst', name: 'Morgan' }]);
	const rows = api.getFlatDatasource();
	if (typeof rows === 'string') throw new Error(rows);
	return rows;
}
Lifecycle and navigation Parameters, result and side effects
init(options?), destroy() Rebuild with partial options, or tear down listeners, observers, generated controls and chart. Both return the API. destroy() is repeatable and sets chart to null; Angular normally handles it.
setOptions(patch), setOptions(key, value) Return the API. Pan, zoom, minimap, zoom limits and export filename/extension/scale update in place. Data, layout and renderer options rebuild; reacquire DOM nodes afterward.
attachMinimap(), detachMinimap(), updateMinimap(forceRefresh?) Create/remove the overlay or synchronously refresh its viewport; pass true to redraw the preview nodes too. Normally use setOptions('minimap', true) to keep the setting in sync. Return void.
setChartScale(chart, multiplier, anchor?) Pass the rendered chart and a positive relative multiplier: 1.2 enlarges the current scale by 20%, within the limits. Optional { x, y } in viewport coordinates stays fixed; defaults to the container center. Returns void.
Editing (all return void) Where the change goes
addParent(currentRoot, data) Wrap the rendered root with one new parent record.
addAncestors(data, parentId) Supply an ancestor tree and the ID in that new tree under which the existing root belongs.
addChildren(node, data), addDescendants(data, parent) Append child records (which may have descendants) or grouped family arrays to a rendered parent. Note the reversed argument order.
addSiblings(node, data) Add an array of peers at the rendered node's level.
removeNodes(node) Remove this node and its whole subtree; removing a tree root tears down its chart.

The engine edits its own records, not your input. After branch rebuilds, reacquire affected node elements. For on-demand loading, fetch records in your application and then call addChildren or addAncestors; a hidden relation does not imply a server request.

Queries and visibility Result
getHierarchy(includeNodeData?) By default returns IDs and children; pass true for node fields too. Family sources retain grouped arrays. A missing chart, empty chart or node without an ID returns an error string.
getFlatDatasource() A depth-first snapshot including hidden nodes; parent_id reflects the current parent, or null at roots. Same error strings as above. Family family_id values are generated per snapshot; use the family converter to restore groups.
getParent(node), getChildren(node), getSiblings(node) Direct relatives as DOM elements: one element or null for parent; arrays (possibly empty) for children and siblings.
getRelatedNodes(node, relation), getNodeState(node, relation) Use 'parent', 'children' or 'siblings'. The first returns the corresponding element(s); the second returns { exist, visible } for loaded relatives.
hideParent(node), showParent(node), hideChildren(node), showChildren(node) Collapse or reveal the related branch without removing its data. Return void.
hideSiblings(node, side?), showSiblings(node, side?) Act on both sides or pass 'left' or 'right' for one side. Return void.

Events and export

Angular outputs are listed under Angular bindings. For native bubbling events, use api.chartContainer.addEventListener(...). Listening on the host survives internal chart replacements. Use the full event name, including .orgchart, and remove application-owned listeners when your view is destroyed.

DOM event When and what to read
init.orgchart After a chart is rendered; event.target is the chart element.
show-children.orgchart, hide-children.orgchart Emitted by the node's edge controls. Substitute parent or siblings for children to observe those controls.
nodedrop.orgchart Before moving a node: event.detail contains draggedNode, dragZone (old parent) and dropZone (new parent). Call event.preventDefault() to veto the move.
otherdropped.orgchart An external item was dropped; read detail.draggedItem and detail.dropZone.
export-error.orgchart Rendering or download failed; the underlying exception is detail.error.

Load the browser bundle providing window.html2canvas before exporting; PDF additionally needs window.jspdf.jsPDF or window.jsPDF. These are optional for chart rendering. See the PDF demo for script order.

Download method Contract
export(filename?, extension?) Uses the option defaults. Returns false if busy or no chart is available; otherwise a promise that resolves to the rendered HTMLCanvasElement after download. Errors reject the promise and emit export-error.orgchart; handle them in the caller.
exportPNG(canvas, filename), exportPDF(canvas, filename, exportScale?) Download a canvas you already have. The filename excludes the extension. PDF scale defaults to 1 and accounts for canvas resolution when sizing the page. Return void.

For styling, set CSS variables on .orgchart in the application's global stylesheet: --oc-node-width, --oc-row-height, --oc-line-color, --oc-hover-color, --oc-control-color, --oc-control-hover-color, --oc-duration. A node's className is useful for department colors. Expand/collapse controls appear on hover; a focused control accepts Enter or Space.

Development

The demo toolbar uses the same Lucide icons as the Vue workbench, in Angular's theme color. Icon-only controls have tooltips and accessible names.

Browse the Angular workbench, or open pan and zoom, on-demand loading or editing. Each of the 46 native previews includes controls for experimenting with layout, editing and data inspection. Standalone Angular usage shows how to use that feature in your own component with @dabeng/angular-orgchart, without the site's controls. Copy the files to the paths shown under the tabs; expand Use this example in your app for any required providers, scripts or downloadable assets. Existing demo/<name>.html bookmarks still open the corresponding preview.

Use Node 24.15+ (24.x) or a compatible version listed in the root package manifest. Run npm ci, then:

Command Result
npm start Demo explorer at http://localhost:4200/; the standalone Angular example is at /home.html.
npm run build Publishable Angular Package Format library in dist/angular-orgchart, and production site in dist/demo/browser.
npm test Original unit and DOM integration suites, plus Angular TestBed/Vitest component contracts.
npm run test:examples Builds the public library, strictly template-checks all 46 standalone file sets in isolation and exercises representative interactions in Angular TestBed.
npm run e2e Starts a local server, runs the Cypress browser suites, and stops the server.

The copyable examples are real Angular files. The live workbench reuses their data and chart options but is not published as raw source. After building the library and npm run build:demo, run node test/standalone/check-sources.mjs --pages to compile the shipped file sets and check their assets. The map example needs network access to OpenStreetMap. The old imperative pages and mount helper are test fixtures only: npm run e2e serves those to the original behavior matrix via the separate compatibility configuration. They are not shipped in the Pages site.

Publishing

Demo site (GitHub Pages): After npm ci, run npm run deploy:demo from a checkout with push access to origin. It builds the app and publishes only dist/demo/browser to the dedicated gh-pages branch, replacing the site's previous files. On the first deployment, select Settings → Pages → Deploy from a branch → gh-pages → / (root) and save. The site homepage lists all examples. Run npm run build:demo to build without pushing. This does not publish an npm package.

If @dabeng/angular-orgchart does not yet exist on npm, publish the first version once from the repository root with npm ci, npm test, npm run build:lib, then npm publish ./dist/angular-orgchart --access public using an account with access to @dabeng.

Before the next release, configure a trusted publisher in the npm package settings: select GitHub Actions, set owner dabeng, repository angular-orgchart, workflow filename publish.yaml, and allow npm publish. Leave the environment name blank. No npm token is needed in GitHub.

For each subsequent release, commit a new version in the library manifest, then tag that commit with the matching v-prefixed version and push the tag. For example, for version 2.0.1:

git tag v2.0.1
git push origin v2.0.1

The publish workflow checks the tag, runs the tests, builds the library and publishes dist/angular-orgchart with provenance. No GitHub Release is required.