0

I am using p-organizationChart to display hierarchy. I am adding child dynamically. After adding child, it's not displaying expand arrow, but when I select any Node then it reflects.

So, I would like to refresh this org-chart programmatically.

Any suggestions?

 <p-organizationChart [value]="programStructure" styleClass="company" selectionMode="single" [(selection)]="selectedParentProgram" #chart [preserveSpace]="false">
</p-organizationChart>

Adding Child:

addChildNode() {
    this.selectedParentProgram.children.push({
        label: this.selectedChildProgram.name,
        type: 'node',
        expanded: true,
        data: {
            'programId': this.selectedChildProgram.id,
            'versionId': this.selectedProgramVersion.id
        },
        children: []
    });
    this.isAddProgramDialogShown = false;
    this.clear();
  }

This code works perfectly as expected. But, chart not getting updated unless I select/unselect any node.

Solution Worked for me

this.cd.detectChanges();
2
  • Please show how you are adding the child. Commented May 21, 2021 at 11:05
  • @MichaelD Added "Adding Child" code above Commented May 21, 2021 at 11:14

1 Answer 1

1

Angular change detection is usually triggered when the reference to an object changes. Adding elements to an array using it's push method wouldn't change the array's reference. Instead you could try to re-assign the variable using the spread syntax.

Try the following

addChildNode() {
  const child = {
    label: this.selectedChildProgram.name,
    type: 'node',
    expanded: true,
    data: {
      'programId': this.selectedChildProgram.id,
      'versionId': this.selectedProgramVersion.id
    },
    children: []
  };
  
  this.selectedParentProgram = {
    ...this.selectedChildProgram,
    children: [
      ...this.selectedChildProgram.children, 
      child
    ]
  };
  this.isAddProgramDialogShown = false;
  this.clear();
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for explanation. Based on above added below line of code and it worked. Thanks a lot. this.cd.detectChanges();
@VaibhavSawant: Yes that would be the other alternative. To manually trigger the change detection when needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.