learner
learner

Reputation: 11

Angular primeng organization chart from api call

I am trying to assign API value to primeng organization chart but not working. it display empty page.I have tried code as follows.

I expect assign API value to primeng organization chart and display the chart.

html

<h1>Org Chart</h1>

<p-organizationChart [value]="data1" selectionMode="single"
    >
    <ng-template let-node pTemplate="person">
        <div class="node-header">{{node.label}}</div>
        <div class="node-content">
            <div>{{node.data.name}}</div>
        </div>
    </ng-template>
    <ng-template let-node pTemplate="department">
        {{node.label}}
    </ng-template>
</p-organizationChart>

ts

ngOnInit(): void {
    this.loadData();
  }

  loadData() {
        this.service.getOrgChartData().subscribe(
      (res) => {
        this.data = res;
        this.root = this.data.d.filter((obj) => obj.OrgLevel == 0)[0];
        this.treeData.label = 'CEO';
        this.treeData.data = { name: 'xxxx' };
        this.treeData.type = 'person';
        this.treeData.expanded = true;
        this.treeData.children = [];
        this.data1.push(this.treeData);
  console.log('-- root data nnn---', this.data1);
      },
      (error) => {
        console.log('error --', error);
      }
    );

Upvotes: 0

Views: 654

Answers (1)

Abutalib
Abutalib

Reputation: 23

For anyone who faces this problem, I solved it by using @ViewChild to reference the organization chart, and refreshed it manually after fetching the data from the API.

In the component:

@ViewChild(OrganizationChart)
  org : OrganizationChart;

Inside your API subscribe method (after loading the data) :

this.org.cd.detectChanges();

Disclaimer:

There are concerns over using this inside ngOnInit() (what I used), and some recommended using another lifecycle hook (AfterViewInit) to guarantee the injection of the chart into your variable. So, use it at your discretion.

Upvotes: 0

Related Questions