I want to image preview multiple images before upload with OnPush change detection strategy.
I try this https://stackblitz.com/edit/angular-mnltiv
When I add OnPush it stop working, I know that I should change the array in a inmutable way but not working
import { Component, ChangeDetectionStrategy } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent {
urls = new Array<string>();
detectFiles(event) {
this.urls = [];
let files = event.target.files;
if (files) {
for (let file of files) {
let reader = new FileReader();
reader.onload = (e: any) => {
this.urls.push(e.target.result);
this.urls = [...this.urls]
}
reader.readAsDataURL(file);
}
}
}
}
I expect this with OnPush https://stackblitz.com/edit/angular-4jmjzh
you have to trigger change detection after updated your url array when using onPush
import { Component, ChangeDetectionStrategy, OnInit, ChangeDetectorRef } from '@angular/core';
constructor(private cdr: ChangeDetectorRef){}
...
detectFiles(event) {
this.urls = [];
let files = event.target.files;
if (files) {
for (let file of files) {
let reader = new FileReader();
reader.onload = (e: any) => {
this.urls = [...this.urls, e.target.result]
this.cdr.detectChanges(); // add this and it should work
}
reader.readAsDataURL(file);
}
}