2

When using *ngFor to render a component multiple times, the components rendered are not updating in DOM as expected.

Rendering the component in an ionic page:

<ion-row *ngFor="let file of files; let i = index">
   <app-add-file (fileEvent)="fileEventHandler(i, $event)"></app-add-file>   //component
</ion-row>

components appear as expected, but when something changes in the component, the change doesn't reflect in the DOM.

Is there a way to force the rerender?

Should I use ChangeDetectorRef inside the component?

Versions:

"@ionic/angular": "^4.7.1",
"@angular/common": "^7.2.2",

would love to provide more data if needed. Thanks!

1
  • 1
    Maybe you can add a simple demo to demostrate your issue in stackblitz.com would be fine. Since it refer to ChangeDetectionStrategy or other things of angular change detection. Commented Dec 17, 2020 at 7:17

1 Answer 1

1

Default change detector has trouble to detect change in array because it compares the instance of the array not the content. If you push something in the array, it remains the same instance so Angular won't start a change dectection.

Fastest solution is the use the [spread operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax to force the change dectection by changing the instance of the array.

myArray.push(data); // won't trigger change detection.
myArray = [...myArray]; // will trigger change detection.

Best solution would be to change the detection strategy of your component to OnPush. You can find more on this solution online.

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.