gpt4 book ai didi

javascript - 使用 changedetection OnPush 进行图像预览

转载 作者:行者123 更新时间:2023-11-30 19:32:16 25 4
gpt4 key购买 nike

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

最佳答案

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

关于javascript - 使用 changedetection OnPush 进行图像预览,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56305190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com