Will
Will

Reputation: 153

Angular: *ngFor not updating view after array changes

I'm making a web app with Angular however I'm having trouble with the load button. So the user presses the load button, selects a save to load, and a new set of properties is loaded into forms that each constitute a step-item in a stepper. The forms array that loads all of the forms is 'reset' with this function:

private resetPropForms(): void {
  this.propForms = [];
}

This is the function that receives as an argument a properties event and then sets the forms array:

onPropertiesEmitted(properties: Property[]): void {
  this.resetPropForms();
  this.resetDividedProperties();
  this.resetUndividedProperties();
  this.setDividedProperties( properties );
  this.setForms();
  this.setUndividedProperties( properties );
}

And this is what my template looks like:

<se-stepper
    *ngIf="undividedProperties"
    [linearMode]="false"
    [(activeStepIndex)]="activeStepIndex"
  >
    <se-step-item
        *ngFor="let form of propForms"
    >
        <app-properties-form
            [propertiesForm]="form"
            (change)="onPropertiesChanged($event)"
        >
        </app-properties-form>
    </se-step-item>

  </se-stepper>

Lastly, the view is updated but only after I go to the next step and come back. And if I save the properties then the correct value is sent to the backend even though the value displayed in the view is incorrect/not updated. Any ideas why this is happening. I tried using trackBy with a unique identifier for each form ( using a random number ) but that didn't work. I tried using ChangesRef and detectChanges() and that didn't work. When I leave out the *ngFor and just display the first form in the array it updates properly so that leads me to believe that this problem has something to do with the *ngFor.

edit:I'm pretty sure setTimeout() placed in onPropertiesEmitted() worked but I forgot where I put it to make it work and it seemed like a not-so-great solution to the problem

Upvotes: 2

Views: 4020

Answers (1)

wFitz
wFitz

Reputation: 1286

I Think the problem is that the array is the same and change detect won't detect changes, try this

private resetPropForms(): void {
  //this.propForms = [];

  //array.slice() returns new array
  this.propForms = this.propForms.slice(0,0);
}

You could also reset the form before assigning new properties ( form.reset() )

Upvotes: 1

Related Questions