1

So, i am pretty new to Angular 5 and in my application i have a component that looks something like this:

//imports

@Component({
  selector: 'dragdropmagic',
  templateUrl: './dragdropmagic.component.html',
  styleUrls: ['./dragdropmagic.component.css']
})
export class DragDropMagicComponent {

  constructor(/*inject services etc*/) {}

  ngOnInit() {
    //init stuff..
  }

  document.getElementById("dragdrop").addEventListener("drop", function (e) {
    e.preventDefault();

    dragDropMagic(e); /*<--- Throws error "Cannot find name 'dragDropMagic'" */
    this.dragDropMagic(e); /*<--- Throws error "Not valid Property for HTML Element" */
  })

  dragDropMagic(e){
    console.log("Do something...");
  }
}

What i am trying to do is call the dragDropMagic function inside the EventListener. How can i achieve this? Normally i would call a method with this.dragDropMagic(e) unfortunately it doesnt seem to work.

rrd
  • 5,789
  • 3
  • 28
  • 36
TheWandererr
  • 514
  • 1
  • 8
  • 34

2 Answers2

1

You need to use @HostListener to handle this.

@HostListener('window:drop', ['$event'])
public dragDrop(event) {
  event.preventDefault();

  // Do your magic;
}

And to find out more on this from someone who has really got a great answer see this SO post as it's very informative and something you can work from to develop your code.

rrd
  • 5,789
  • 3
  • 28
  • 36
1

Instead of calling addEventListener, you can bind the dragDropMagic method to the drop event of your drop zone in the component template, as shown in this stackblitz:

<div (dragover)="$event.preventDefault()" (drop)="dragDropMagic($event)">Drop area</div>
dragDropMagic(event: DragEvent) {
  event.preventDefault();
  console.log("Do something...");
}
ConnorsFan
  • 70,558
  • 13
  • 122
  • 146