2

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?
      }
   });
}
Julien
  • 101
  • 2
  • 12
  • Possible duplicate of [Angular 2: How to detect changes in an array? (@input property)](https://stackoverflow.com/questions/42962394/angular-2-how-to-detect-changes-in-an-array-input-property) – Kim Kern Jan 30 '18 at 22:52

1 Answers1

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();
Kim Kern
  • 54,283
  • 17
  • 197
  • 195