niio
niio

Reputation: 346

Angular2 Output EventEmitter.emit not working

I have created file upload directive with drag&drop functionality. Weird part is, that it is working, when file is selected from opened window, but not working, when file is drag&dropped, even if whole logic is the same and variables have the same values. Code below does not emit event, even if the code runs to the .emit line

    @Output() public fileSelect: EventEmitter<File> = new EventEmitter<File>();

    @HostListener('drop', ['$event'])
  public onDrop(event: any): void {
    console.log("drop");
    const transfer = this.getDataTransfer(event);

    if (!transfer) {
      return;
    }

    this.preventAndStop(event);
    this.emitFileOver(false);

    this.handleFiles(transfer.files);
  }

    private emitFileSelect(file: any): void {
    this.fileSelect.emit(file);
  }

The difference between drag&drop and selecting file from window is just in listener. Code below opens select windows, and when file gets selected, the handleFiles is called, exactly like in drag&drop event.

@HostListener('change', ['$event'])
  public onChange(event) {
    console.log("change");
    this.handleFiles(event.srcElement.files);
  }

as you can see both listeners are calling handleFiles with the same parameter value ( I debugged it). The whole code:

   import { FileUploadState, FileOptions } from './file-drop.models';
import {
  Directive,
  EventEmitter,
  ElementRef,
  HostListener,
  Input,
  Output
} from '@angular/core';

@Directive({ selector: '[pdFileDrop]' })
export class FileDropDirective {
  @Output()
  public fileOver: EventEmitter<boolean> = new EventEmitter<boolean>();
  @Output()
  public fileUploadState: EventEmitter<FileUploadState> = new EventEmitter<
    FileUploadState
    >();
  @Output() public fileSelect: EventEmitter<File> = new EventEmitter<File>();
  @Input() public options: FileOptions;

  private element: ElementRef;

  public constructor(element: ElementRef) {
    this.element = element;
    this.element.nativeElement.setAttribute('multiple', 'multiple');
  }

  @HostListener('dragover', ['$event'])
  public onDragOver(event: any): void {
    console.log("dragOver");
    const transfer = this.getDataTransfer(event);

    if (!this.haveFiles(transfer.types)) {
      return;
    }

    transfer.dropEffect = 'copy';
    this.preventAndStop(event);
    this.emitFileOver(true);
  }

  @HostListener('dragleave', ['$event'])
  public onDragLeave(event: any): void {
    console.log("dragLeave");
    if (event.currentTarget === (this as any).element[0]) {
      return;
    }

    this.preventAndStop(event);
    this.emitFileOver(false);
  }

  @HostListener('drop', ['$event'])
  public onDrop(event: any): void {
    console.log("drop");
    const transfer = this.getDataTransfer(event);

    if (!transfer) {
      return;
    }

    this.preventAndStop(event);
    this.emitFileOver(false);

    this.handleFiles(transfer.files);
  }

  @HostListener('change', ['$event'])
  public onChange(event) {
    console.log("change");
    this.handleFiles(event.srcElement.files);
  }

  ngOnInit() {
    console.log("Observers: " + this.fileSelect.observers.length);
  }

  private handleFiles(files: any) {
    console.log("handleFiles");
    // check all files
    for (let i = 0; i < files.length; i++) {
      console.log(i);
      const fileUploadState = <FileUploadState>{};
      const isFileTypeSupported = this.isFileTypeSupported(files[i].name);
      const isFileSizeAllowed = this.isFileSizeAllowed(files[i].size);

      fileUploadState.fileTypeNotAllowedError = !isFileTypeSupported;
      fileUploadState.fileSizeToBigError = !isFileSizeAllowed;
      fileUploadState.error = !isFileTypeSupported || !isFileSizeAllowed;
      fileUploadState.done = false;
      fileUploadState.file = files[i];
      this.emitFileSelect(fileUploadState);
    }
  }

  private emitFileOver(isOver: boolean): void {
    this.fileOver.emit(isOver);
  }

  private emitFileSelect(file: any): void {
    this.fileSelect.emit(file);
  }

  private isFileTypeSupported(fileName: string): boolean {
    if (!this.options) {
      return true;
    } else if (!this.options.supportedFilesTypes) {
      return true;
    } else {
      return (
        this.options.supportedFilesTypes.indexOf(
          this.getFileExtensionFromFileName(fileName).toLowerCase()
        ) !== -1
      );
    }
  }
  private isFileSizeAllowed(fileSize: number) {
    if (!this.options) {
      return true;
    } else if (!this.options.maxUploadSizeInMb) {
      return true;
    } else {
      return fileSize / 1000000 <= this.options.maxUploadSizeInMb;
    }
  }

  private getDataTransfer(event: any | any): DataTransfer {
    return event.dataTransfer
      ? event.dataTransfer
      : event.originalEvent.dataTransfer;
  }

  private preventAndStop(event: any): void {
    event.preventDefault();
    event.stopPropagation();
  }
  private getFileExtensionFromFileName(fileName: string): string {
    return fileName.substr(fileName.lastIndexOf('.') + 1);
  }
  private haveFiles(types: any): boolean {
    if (!types) {
      return false;
    }

    if (types.indexOf) {
      return types.indexOf('Files') !== -1;
    }

    if (types.contains) {
      return types.contains('Files');
    }

    return false;
  }
}

The emited event is catched in component. In case of when file is selected, the code execution runs like expected into this fileSelect($event) function (see below), in case of drg&drop the code execution ends on the .emit line of the emitFileSelect function (see above).

<label pdFileDrop [options]="options" (change)="fileSelect($event)">
          <input type="file" />
        </label>

fileSelect($event) {
const that = this;
const reader = new FileReader();
const image = $event.target.closest('.box').querySelectorAll('img')[0];
$event.target.closest('.box').classList.add('thumb-shown');

reader.onload = function (event) {
  if (event && event.target && event.target['result']) {
    image.src = event.target['result'];
    that._file.id = that.id;
    that._file.src = event.target['result'];
    that.attachmentForm.controls['fileName'].patchValue(
      $event.target.files[0].name
    );
    that._file.description = $event.target.files[0].name; //fileName;
    that._file.rotation = that.rotateDeg;
    that._file.thumbnail = image.src;
    that._file.fileType = that.getFileType(image.src);
  }
};

Maybe the preventAndStop function, which prevents the browser to redirect to the dropped file path and show the file in browser, is also blocking the .emit event? UPDATE: preventAndStop function is not blocking event.emit.

Upvotes: 1

Views: 7079

Answers (2)

niio
niio

Reputation: 346

So the issue was in the

<label pdFileDrop [options]="options" (change)="fileSelect($event)">
          <input type="file" />
        </label>

I need to listen to the EventEmitter, not change event. So correct should be:

<label pdFileDrop [options]="options" (fileSelect)="fileSelect($event)">
          <input type="file" />
        </label>

And some code adaptation is needed, but finally the d&d is working.

Upvotes: 0

Joshua Chan
Joshua Chan

Reputation: 1847

You are using Output EventEmitter wrongly:

Try (fileSelect)="fileSelect($event)" instead of (change)="fileSelect($event)

Upvotes: 6

Related Questions