Repository navigation
Expand file tree
/
Copy pathondemand-loading-data.component.ts
More file actions
61 lines (58 loc) · 2.59 KB
/
Copy pathondemand-loading-data.component.ts
File metadata and controls
61 lines (58 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { Component, DestroyRef, signal, inject, viewChild } from '@angular/core';
import { OrgChartComponent, type ChartOptions, type ChartNode } from '@dabeng/angular-orgchart';
import team from './data/ondemand-loading-data.json';
import { HttpClient } from '@angular/common/http';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
export const chartOptions: ChartOptions = {
nodeContent: "title",
nodeId: "id"
};
@Component({
selector: 'example-ondemand-loading-data',
imports: [OrgChartComponent],
template: `
<ng-template #personTemplate let-person>
<div class="title">{{ person.name }}</div><div class="content">{{ person.title }}</div>
@if (urls['descendants-' + person.id]) {
<button [disabled]="requested().has('descendants-' + person.id)" (click)="load('descendants', person)">Load children</button>
}
@if (urls['ancestors-' + person.id]) {
<button [disabled]="requested().has('ancestors-' + person.id)" (click)="load('ancestors', person)">Load ancestors</button>
}
</ng-template>
@if (error()) { <p role="alert">{{ error() }}</p> }
<angular-orgchart [data]="data" [options]="options" [nodeTemplate]="personTemplate" />
`
})
export class DemoOndemandLoadingData {
readonly data = team;
readonly options = chartOptions;
readonly urls: Record<string, string> = {
"ancestors-n1": "data/ancestors-n1.json",
"descendants-n2": "data/descendants-n2.json",
"descendants-n3": "data/descendants-n3.json"
};
readonly requested = signal(new Set<string>());
readonly error = signal('');
private readonly chart = viewChild.required(OrgChartComponent);
private readonly destroyRef = inject(DestroyRef);
private readonly http = inject(HttpClient);
load(relation: 'descendants' | 'ancestors', person: ChartNode) {
const key = relation + '-' + person['id'];
const api = this.chart().api();
const node = api?.chart?.querySelector<HTMLElement>('#' + CSS.escape(String(person['id'])));
if (!api || !node || !this.urls[key] || this.requested().has(key)) return;
this.error.set('');
this.requested.update(previous => new Set(previous).add(key));
this.http.get<ChartNode | ChartNode[]>(this.urls[key]).pipe(takeUntilDestroyed(this.destroyRef)).subscribe({
next: result => {
if (Array.isArray(result)) api.addDescendants(result, node);
else api.addAncestors(result, String(result['id']));
},
error: error => {
this.error.set(error.message);
this.requested.update(previous => { const next = new Set(previous); next.delete(key); return next; });
}
});
}
}