Angular (ionic): rendering component with loop: component's view doesn't update

Viewed 450

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 Answers

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.

Related