0
votes

I have a problem with Angular drag and drop. I created a component and a directive for it. I tried two solutions, this is the first:

@HostListener('drop', ['$event']) public onDrop(evt) {
        evt.preventDefault();
        evt.stopPropagation();
        this.background = '#eee';
        let files = evt.dataTransfer.files;
        let valid_files: Array<File> = [];
        let invalid_files: Array<File> = [];
        if (files.length > 0) {
            files.forEach((file: File) => {
                let ext = file.name.split('.')[file.name.split('.').length - 1];
                if (this.allowed_extensions.lastIndexOf(ext) !== -1) {
                    valid_files.push(file);
                } else {
                    invalid_files.push(file);
                }
            });
            this.filesChangeEmiter.emit(valid_files);
            this.filesInvalidEmiter.emit(invalid_files);
        }
    }

I got an error message when I drop the image to the browser.

files.forEach is not a function

And I tried a different forEach like this:

import { forEach } from '@angular/router/src/utils/collection';

@HostListener('drop', ['$event']) public onDrop(evt) {
        evt.preventDefault();
        evt.stopPropagation();
        this.background = '#eee';
        let files = evt.dataTransfer.files;
        let valid_files: Array<File> = [];
        let invalid_files: Array<File> = [];
        if (files.length > 0) {
           forEach(files, (file: File) => {
                let ext = file.name.split('.')[file.name.split('.').length - 1];
                if (this.allowed_extensions.lastIndexOf(ext) !== -1) {
                    valid_files.push(file);
                } else {
                    invalid_files.push(file);
                }
            });
            this.filesChangeEmiter.emit(valid_files);
            this.filesInvalidEmiter.emit(invalid_files);
        }
    }

This way I got an error message like this:

./src/app/hotels/drag-n-drop/drag-n-drop.directive.ts
Module not found: Error: Can't resolve '@angular/router/src/utils/collection' in '/Users/MrFox/OneDrive/greenfox/hotel-booking-admin-frontend/src/app/hotels/drag-n-drop'
@ ./src/app/hotels/drag-n-drop/drag-n-drop.directive.ts 11:0-63
@ ./src/app/app.module.ts
@ ./src/main.ts
@ multi webpack-dev-server/client?http://localhost:4200 ./src/main.ts

I already imported it to the app.module.

1

1 Answers

0
votes

I have the solution, you need to use a regular for loop instead of the forEach.