0

當使用遞歸函數讀取用戶的拖動文件時,我遇到了使用角度2更改檢測的奇怪問題&。使用遞歸函數的角度2更改檢測問題

參考這裏的例子:

File drop example: plnkr.co

在上面的例子中,有兩個文件拖放區域。頂部區域使用遞歸函數來讀取用戶丟棄項目中的所有文件。底部區域只需使用dataTransfer.files

丟棄的文件應該顯示在下面。但是,更改檢測僅適用於底部區域。

這是我的實際應用程序的簡化版本。我並不熱衷於使用ChangeDetectorRef來觸發檢測(我知道這將適用於笨重的例子)。

有沒有更好的方法來讀取webkitGetAsEntry()中的所有文件(包括子文件夾中的文件)? 或者另一種方式將與角度變化檢測一起工作?

我在Angular 2.4.9上。感謝幫助。

+0

您需要在角區域內運行代碼http://take.ms/bbKa3 – yurzui

+0

@yurzui謝謝!但是你知道爲什麼遞歸函數在'NgZone'之外運行嗎? – Northern

+0

angular(zonejs)不會修補'FileEntry.file' – yurzui

回答

0

用下面的代碼替換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 {} 
+0

感謝您的回答。我認爲上面的評論給出了一個更好的建議。文件放置指令可能會被許多組件使用。修改指令本身中的變化檢測比使用它的所有組件更好。我仍然不確定爲什麼遞歸函數在'NgZone'之外運行。如果你願意,請告訴我。 – Northern