Javascript 使用changedetection OnPush进行图像预览
我想在上传前使用OnPush更改检测策略预览多张图像 我试试这个 当我添加OnPush时,它停止工作,我知道我应该以一种不可变的方式更改数组,但不工作Javascript 使用changedetection OnPush进行图像预览,javascript,angular,angular-changedetection,Javascript,Angular,Angular Changedetection,我想在上传前使用OnPush更改检测策略预览多张图像 我试试这个 当我添加OnPush时,它停止工作,我知道我应该以一种不可变的方式更改数组,但不工作 import { Component, ChangeDetectionStrategy } from '@angular/core'; import { FormsModule } from '@angular/forms'; @Component({ selector: 'my-app', templateUrl: './app.c
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);
}
}
}
}
从'@angular/core'导入{Component,ChangeDetectionStrategy};
从'@angular/forms'导入{FormsModule};
@组成部分({
选择器:“我的应用程序”,
templateUrl:“./app.component.html”,
样式URL:['./app.component.css'],
changeDetection:ChangeDetectionStrategy.OnPush
})
导出类AppComponent{
URL=新数组();
检测文件(事件){
this.url=[];
让files=event.target.files;
如果(文件){
for(让文件中的文件){
let reader=new FileReader();
reader.onload=(e:any)=>{
this.url.push(例如target.result);
this.url=[…this.url]
}
reader.readAsDataURL(文件);
}
}
}
}
我希望这是一次推送
使用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);
}
}
使用
detectChanges()
而不是markForCheck()
的具体原因是什么?