Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular : how to trigger bindings manually?

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?
      }
   });
}
like image 678
Julien Avatar asked Jul 04 '26 12:07

Julien


1 Answers

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();
like image 146
Kim Kern Avatar answered Jul 06 '26 02:07

Kim Kern



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!