簡體   English   中英

遞歸函數的Angular 2變化檢測問題

[英]Angular 2 change detection issue with recursive function

使用遞歸函數讀取用戶拖放文件時,Angular 2更改檢測遇到一個奇怪的問題。

請參考此處的示例:

文件刪除示例:plnkr.co

在上面的示例中,有兩個文件放置區域。 頂部區域使用遞歸功能來讀取用戶放置的項目中的所有文件。 底部區域僅使用dataTransfer.files

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

這是我實際應用程序的簡化版本。 我不希望使用ChangeDetectorRef觸發檢測(我知道它將適用於更簡單的示例)。

是否有更好的方法通過webkitGetAsEntry()讀取放入的所有文件(包括子文件夾中的文件webkitGetAsEntry() 還是有其他方法可以用於角度變化檢測?

我使用的是Angular 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 {}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM