Thursday, 14 February 2019

refactoring code from ChangeDetectionStrategy.Default to ChangeDetectionStrategy.OnPush

I'm new to angular after spending the last few years on react projects.

I have a component that is using changeDetection: ChangeDetectionStrategy.OnPush and I don't like my solution. The trouble is that I am finding it tough to find any good real world examples of ChangeDetectionStrategy.OnPush

For example, I have a component a bit like this:

  files: Uploads[] = [];

  get canUpload() {
    return this.files.length > 0l
  }

  get isUploading() {
    return this.files.length > 0 && this.files.some((f) => f.state === FileUpLoadState.uploading);
  }

  get activeFiles() {
    return this.files.filter((f) => f.state !== FileUpLoadState.success);
  }

  uploadFiles() {
    if (!this.files.length) {
      return;
    }

    const fileList: FileList = (event.target as HTMLInputElement).files;

    for (const uploadedFile of Array.prototype.slice.call(fileList)) {
      // do stuff
      this.files.push(new Upload(file));
    }

  }

I have these properties that are used in the template like this;

 <button (click)="uploadFiles()" [disabled]="!this.canUpload">Upload</button>

I really don't like this, using default change detection won't scale and when changes get propagated are outside of my control.

How can I refactor this code to use OnPush change detection?



from refactoring code from ChangeDetectionStrategy.Default to ChangeDetectionStrategy.OnPush

No comments:

Post a Comment