Javascript 带递归函数的角度2变化检测问题
在使用递归函数读取用户拖放文件时,我遇到了一个关于Angular 2更改检测的奇怪问题 有关示例,请参阅此处: 在上面的示例中,有两个文件放置区域。顶部区域使用递归函数读取用户删除项中的所有文件。底部区域只需使用Javascript 带递归函数的角度2变化检测问题,javascript,angular,dom-events,angular2-changedetection,virtual-dom,Javascript,Angular,Dom Events,Angular2 Changedetection,Virtual Dom,在使用递归函数读取用户拖放文件时,我遇到了一个关于Angular 2更改检测的奇怪问题 有关示例,请参阅此处: 在上面的示例中,有两个文件放置区域。顶部区域使用递归函数读取用户删除项中的所有文件。底部区域只需使用dataTransfer.files 删除的文件应该显示在下面。但是,更改检测仅适用于底部下降区域 这是我实际应用程序的简化版本。我不喜欢使用ChangeDetectorRef来触发检测(我知道它对plunker示例有效) 使用webkitGetAsEntry(),是否有更好的方法读取
dataTransfer.files
删除的文件应该显示在下面。但是,更改检测仅适用于底部下降区域
这是我实际应用程序的简化版本。我不喜欢使用ChangeDetectorRef
来触发检测(我知道它对plunker示例有效)
使用webkitGetAsEntry()
,是否有更好的方法读取放入的所有文件(包括子文件夹中的文件)?
或者用另一种方法检测角度变化
我在角2.4.9上 用下面的代码替换app.ts中的代码,它将正常工作。Zone.js将在执行回调后检测更改
//our root app component
import {Component, NgModule,NgZone} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import { FileDropDirective } from './file.drop.directive'
@Component({
selector: 'my-app',
template: `
<div>
<div file-drop class="drop-area" readAsItems="yes"
(droppedFiles)="onFilesDrop($event)">Recursive func</div>
<div file-drop class="drop-area"
(droppedFiles)="onFilesDrop($event)">Non-recursive func</div>
<div *ngFor="let f of files">{{ f }}</div>
</div>
`,
styles: [`
.drop-area {
width: 100%;
height: 20vh;
background-color: #f1f1f1;
border: 1px solid red;
margin: 5px 0;
}
`]
})
export class App {
name:string;
files: string[];
constructor(private zone:NgZone) {
this.name = 'Angular2'
this.files = [];
}
onFilesDrop(files) {
this.zone.run(()=>{
files.forEach((f) => {
this.files.push(f.name);
})
console.log(this.files);
});
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App, FileDropDirective ],
bootstrap: [ App ]
})
export class AppModule {}
//我们的根应用程序组件
从“@angular/core”导入{Component,NgModule,NgZone}
从“@angular/platform browser”导入{BrowserModule}
从“./file.drop.directive”导入{FileDropDirective}
@组成部分({
选择器:“我的应用程序”,
模板:`
递归函数
非递归函数
{{f}}
`,
风格:[`
.降落区{
宽度:100%;
高度:20vh;
背景色:#f1f1;
边框:1px纯红;
保证金:5px0;
}
`]
})
导出类应用程序{
名称:字符串;
文件:字符串[];
建造商(专用区:NgZone){
this.name='Angular2'
this.files=[];
}
onFileDrop(文件){
此.zone.run(()=>{
files.forEach((f)=>{
this.files.push(f.name);
})
console.log(this.files);
});
}
}
@NGD模块({
导入:[BrowserModule],
声明:[App,FileDropDirective],
引导:[应用程序]
})
导出类AppModule{}
您需要在angular zone@yurzui内运行代码,谢谢!但是你知道为什么递归函数在NgZone
之外运行吗?angular(zonejs)不修补FileEntry.file
@yurzui你能详细解释一下“不修补FileEntry.file”是什么意思吗?我还有另一个调用this.addFiles(files)
,它在NgZone
中运行良好。我能看到的唯一区别是第二个调用在递归函数中。谢谢你的回答。我认为上面yurzui的评论给出了一个更好的建议。file drop指令可能会被许多组件使用。在指令本身中修复更改检测比在使用它的所有组件中修复更改检测更好。我仍然不确定递归函数为什么在NgZone
之外运行。如果有,请告诉我。