带有changedetection OnPush的图像预览

时间:2019-05-25 13:19:21

标签: javascript angular angular-changedetection

我想在使用OnPush更改检测策略上传之前预览多张图像。

我尝试这个 https://stackblitz.com/edit/angular-mnltiv

当我添加OnPush时,它停止工作,我知道我应该以不变的方式更改数组,但不能工作

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);
      }
    }
  }
}

我希望OnPush能做到这一点 https://stackblitz.com/edit/angular-4jmjzh

1 个答案:

答案 0 :(得分:1)

使用onPush更新URL数组后,您必须触发更改检测

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);
  }
}