1

我想在使用 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

4

1 回答 1

2

使用 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);
  }
}
于 2019-05-25T14:18:25.437 回答