Angular Material Table "trackBy" causes formControl.valueChanges to be out of sync with Model and View

Viewed 18

I am using a trackBy function on an Angular mat-table component that is itself part of an angular reactive formControl.

My table is initiated with a single row on ngInit. That row contains a material-input mat-autocomplete component control in the first cell and a hidden input component in the second cell. The value of the hidden component is data bound to always track with the value of the material-input.

This works as expected. I can see in the chrome dev tools by observing the dom objects that as I change the value of the mat-input, the hidden input's value changes as expected.

Now, for the trackBy behavior...

I have an "Add Row" button whose (click) event activates an "addRow" method that adds a new table row to the end of the table. This new consists of the mat-input and the hidden input.

I can see from the chrome inspector tools that when I add a new row to my mat-table only the newly added row is redrawn in the DOM. All good so far, this is the expected behavior.

However, when I modify a previously added row, shouldn't I expect to see that row light up in the DOM and redrawn? I can certainly see that the formControls in the DOM for that row have changed values, but because of the trackBy, the formControl.valueChanges never fires and console log of the formControl.

Is this expected behavior?

As a result, when I click a button on my form that logs the value for each of the controls in the formGroup to the console, the rows that trackBy have apparently cached always show the initial values they were set to and no longer show the updated values that I can clearly see they are set to in the DOM:

showFieldValues() {
 Object.keys(this.formGroup.controls).forEach(key => {
   console.log(key, ': ', this.formGroup.controls[key].value);
 });
}
0 Answers
Related