3

I've an angular material 5 component with an array of objects. It displays a modal dialog opening another component with a form to modify one object of the array.

When my dialog get closed, it sends back the modified object. So the parent take this result and update the array. But the displays does not get updated and this my issue.

Either my logic is wrong or I need to manually re-trigger the binding? What would you suggest?

Here the function opening the dialog and updating the array after it's been closed.

openDialog(event: any, id: number) {
     const index = this.contractors.findIndex(x => x.Id === id); 

     const dialogRef = this.dialog.open(ContractorEditComponent, {
     width: '600px',
     data: { contractor : this.contractors[index] }
   });

   dialogRef.afterClosed().subscribe( (contractor: ContractorModel) => {
      if (contractor !== null) {
         this.contractors[index] = contractor; // update my collection with new value
         // Should I re-trigger data binding manually here to update the UI?
      }
   });
}
1

1 Answer 1

2

Angular's change detection will only trigger, when a new object is referenced but not when an object is modified. With this.contractors[index] = contractor, you only modify the array but the reference itself stays the same.

There are several different ways to solve this problem, like creating a new copy of the array, using Observables or manually triggering change detection by injecting and using ChangeDetectorRef:

constructor(private ref: ChangeDetectorRef) {}
// ...
this.ref.detectChanges();
Sign up to request clarification or add additional context in comments.

Comments

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.