HTML 5 Drag & Drop with Angular 4












7















I am trying to get the native HTML 5 drag & drop working in my angular app. I got the drag, fire the drag & the dragOver events, but the drop unfortunately doesn't fire anything. Here I have the HTML and drag events code below.



<ul *ngFor="let channel of channelList" >
<li class="list-group-item" *ngIf="channel.channel.substr(0, 1) === head"
style="float:left; margin:0.5px" draggable="true" (dragstart)="drag(channel)">
<ng-container *ngIf="channel.compChannel.compChannelLogo.length !== 0; else noCompChannel">
<img class="img-rounded" src="{{ channel.logo }}" alt="{{ channel.channel }}" width="100" height="100">
<img class="img-rounded" src="{{ channel.compChannel.compChannelLogo }}" alt="{{ channel.channel.compChannelName }}" width="100" height="100">
</ng-container>
<ng-template #noCompChannel>
<img class="img-rounded" src="{{ channel.logo }}" alt="{{ channel.channel }}"
width="100" height="100" >
</ng-template>
</li>
</ul>
<ul class="list-group" *ngFor="let channels of currentPickSelection" dropzone="copy">
<li class="list-group-item" style="float:Left; margin-left:0.5px" (dragover)="dragOver(channels[0])" (dragend)="drop(event)">
<ng-container *ngIf="channels[0].compChannel.compChannelLogo.length !== 0; else noCompChannel">
<img class="img-rounded" src="{{ channels[0].logo }}" alt="{{ channels[0].channel }}" width="70" height="70">
<img class="img-rounded" src="{{ channels[0].compChannel.compChannelLogo }}" alt="{{ channels[0].compChannel.compChannelName }}"
width="70" height="70">
</ng-container>
<ng-template #noCompChannel>
<img class="img-rounded" src="{{ channels[0].logo }}" alt="{{ channels[0].channel }}" width="70" height="70">
</ng-template>
<br>
<strong>
<font size="2">{{ channels[0].pickCode }}</font>
</strong>
</li>
</ul>



drag(channel) {
console.log(channel);
}
dragOver(channel) {
this.draggedChannel = channel;
// console.log(this.draggedChannel);
}

drop(e) {
console.log(e);
}









share|improve this question























  • Have you used any Library or Package for drag n drop?

    – hrdkisback
    Dec 26 '17 at 9:30











  • No I am just using the native HTML 5

    – Sumchans
    Dec 26 '17 at 9:38











  • Have you tried ondrop="drop(event)" ?

    – hrdkisback
    Dec 26 '17 at 10:02











  • drop doesn't fire at all.

    – Sumchans
    Dec 26 '17 at 17:27
















7















I am trying to get the native HTML 5 drag & drop working in my angular app. I got the drag, fire the drag & the dragOver events, but the drop unfortunately doesn't fire anything. Here I have the HTML and drag events code below.



<ul *ngFor="let channel of channelList" >
<li class="list-group-item" *ngIf="channel.channel.substr(0, 1) === head"
style="float:left; margin:0.5px" draggable="true" (dragstart)="drag(channel)">
<ng-container *ngIf="channel.compChannel.compChannelLogo.length !== 0; else noCompChannel">
<img class="img-rounded" src="{{ channel.logo }}" alt="{{ channel.channel }}" width="100" height="100">
<img class="img-rounded" src="{{ channel.compChannel.compChannelLogo }}" alt="{{ channel.channel.compChannelName }}" width="100" height="100">
</ng-container>
<ng-template #noCompChannel>
<img class="img-rounded" src="{{ channel.logo }}" alt="{{ channel.channel }}"
width="100" height="100" >
</ng-template>
</li>
</ul>
<ul class="list-group" *ngFor="let channels of currentPickSelection" dropzone="copy">
<li class="list-group-item" style="float:Left; margin-left:0.5px" (dragover)="dragOver(channels[0])" (dragend)="drop(event)">
<ng-container *ngIf="channels[0].compChannel.compChannelLogo.length !== 0; else noCompChannel">
<img class="img-rounded" src="{{ channels[0].logo }}" alt="{{ channels[0].channel }}" width="70" height="70">
<img class="img-rounded" src="{{ channels[0].compChannel.compChannelLogo }}" alt="{{ channels[0].compChannel.compChannelName }}"
width="70" height="70">
</ng-container>
<ng-template #noCompChannel>
<img class="img-rounded" src="{{ channels[0].logo }}" alt="{{ channels[0].channel }}" width="70" height="70">
</ng-template>
<br>
<strong>
<font size="2">{{ channels[0].pickCode }}</font>
</strong>
</li>
</ul>



drag(channel) {
console.log(channel);
}
dragOver(channel) {
this.draggedChannel = channel;
// console.log(this.draggedChannel);
}

drop(e) {
console.log(e);
}









share|improve this question























  • Have you used any Library or Package for drag n drop?

    – hrdkisback
    Dec 26 '17 at 9:30











  • No I am just using the native HTML 5

    – Sumchans
    Dec 26 '17 at 9:38











  • Have you tried ondrop="drop(event)" ?

    – hrdkisback
    Dec 26 '17 at 10:02











  • drop doesn't fire at all.

    – Sumchans
    Dec 26 '17 at 17:27














7












7








7


2






I am trying to get the native HTML 5 drag & drop working in my angular app. I got the drag, fire the drag & the dragOver events, but the drop unfortunately doesn't fire anything. Here I have the HTML and drag events code below.



<ul *ngFor="let channel of channelList" >
<li class="list-group-item" *ngIf="channel.channel.substr(0, 1) === head"
style="float:left; margin:0.5px" draggable="true" (dragstart)="drag(channel)">
<ng-container *ngIf="channel.compChannel.compChannelLogo.length !== 0; else noCompChannel">
<img class="img-rounded" src="{{ channel.logo }}" alt="{{ channel.channel }}" width="100" height="100">
<img class="img-rounded" src="{{ channel.compChannel.compChannelLogo }}" alt="{{ channel.channel.compChannelName }}" width="100" height="100">
</ng-container>
<ng-template #noCompChannel>
<img class="img-rounded" src="{{ channel.logo }}" alt="{{ channel.channel }}"
width="100" height="100" >
</ng-template>
</li>
</ul>
<ul class="list-group" *ngFor="let channels of currentPickSelection" dropzone="copy">
<li class="list-group-item" style="float:Left; margin-left:0.5px" (dragover)="dragOver(channels[0])" (dragend)="drop(event)">
<ng-container *ngIf="channels[0].compChannel.compChannelLogo.length !== 0; else noCompChannel">
<img class="img-rounded" src="{{ channels[0].logo }}" alt="{{ channels[0].channel }}" width="70" height="70">
<img class="img-rounded" src="{{ channels[0].compChannel.compChannelLogo }}" alt="{{ channels[0].compChannel.compChannelName }}"
width="70" height="70">
</ng-container>
<ng-template #noCompChannel>
<img class="img-rounded" src="{{ channels[0].logo }}" alt="{{ channels[0].channel }}" width="70" height="70">
</ng-template>
<br>
<strong>
<font size="2">{{ channels[0].pickCode }}</font>
</strong>
</li>
</ul>



drag(channel) {
console.log(channel);
}
dragOver(channel) {
this.draggedChannel = channel;
// console.log(this.draggedChannel);
}

drop(e) {
console.log(e);
}









share|improve this question














I am trying to get the native HTML 5 drag & drop working in my angular app. I got the drag, fire the drag & the dragOver events, but the drop unfortunately doesn't fire anything. Here I have the HTML and drag events code below.



<ul *ngFor="let channel of channelList" >
<li class="list-group-item" *ngIf="channel.channel.substr(0, 1) === head"
style="float:left; margin:0.5px" draggable="true" (dragstart)="drag(channel)">
<ng-container *ngIf="channel.compChannel.compChannelLogo.length !== 0; else noCompChannel">
<img class="img-rounded" src="{{ channel.logo }}" alt="{{ channel.channel }}" width="100" height="100">
<img class="img-rounded" src="{{ channel.compChannel.compChannelLogo }}" alt="{{ channel.channel.compChannelName }}" width="100" height="100">
</ng-container>
<ng-template #noCompChannel>
<img class="img-rounded" src="{{ channel.logo }}" alt="{{ channel.channel }}"
width="100" height="100" >
</ng-template>
</li>
</ul>
<ul class="list-group" *ngFor="let channels of currentPickSelection" dropzone="copy">
<li class="list-group-item" style="float:Left; margin-left:0.5px" (dragover)="dragOver(channels[0])" (dragend)="drop(event)">
<ng-container *ngIf="channels[0].compChannel.compChannelLogo.length !== 0; else noCompChannel">
<img class="img-rounded" src="{{ channels[0].logo }}" alt="{{ channels[0].channel }}" width="70" height="70">
<img class="img-rounded" src="{{ channels[0].compChannel.compChannelLogo }}" alt="{{ channels[0].compChannel.compChannelName }}"
width="70" height="70">
</ng-container>
<ng-template #noCompChannel>
<img class="img-rounded" src="{{ channels[0].logo }}" alt="{{ channels[0].channel }}" width="70" height="70">
</ng-template>
<br>
<strong>
<font size="2">{{ channels[0].pickCode }}</font>
</strong>
</li>
</ul>



drag(channel) {
console.log(channel);
}
dragOver(channel) {
this.draggedChannel = channel;
// console.log(this.draggedChannel);
}

drop(e) {
console.log(e);
}






html angular typescript drag-and-drop






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Dec 26 '17 at 7:23









SumchansSumchans

1981518




1981518













  • Have you used any Library or Package for drag n drop?

    – hrdkisback
    Dec 26 '17 at 9:30











  • No I am just using the native HTML 5

    – Sumchans
    Dec 26 '17 at 9:38











  • Have you tried ondrop="drop(event)" ?

    – hrdkisback
    Dec 26 '17 at 10:02











  • drop doesn't fire at all.

    – Sumchans
    Dec 26 '17 at 17:27



















  • Have you used any Library or Package for drag n drop?

    – hrdkisback
    Dec 26 '17 at 9:30











  • No I am just using the native HTML 5

    – Sumchans
    Dec 26 '17 at 9:38











  • Have you tried ondrop="drop(event)" ?

    – hrdkisback
    Dec 26 '17 at 10:02











  • drop doesn't fire at all.

    – Sumchans
    Dec 26 '17 at 17:27

















Have you used any Library or Package for drag n drop?

– hrdkisback
Dec 26 '17 at 9:30





Have you used any Library or Package for drag n drop?

– hrdkisback
Dec 26 '17 at 9:30













No I am just using the native HTML 5

– Sumchans
Dec 26 '17 at 9:38





No I am just using the native HTML 5

– Sumchans
Dec 26 '17 at 9:38













Have you tried ondrop="drop(event)" ?

– hrdkisback
Dec 26 '17 at 10:02





Have you tried ondrop="drop(event)" ?

– hrdkisback
Dec 26 '17 at 10:02













drop doesn't fire at all.

– Sumchans
Dec 26 '17 at 17:27





drop doesn't fire at all.

– Sumchans
Dec 26 '17 at 17:27












7 Answers
7






active

oldest

votes


















9














I made it without any other module in Angular 2/4/5/6, You can also make it by using below code:



drag.component.html:



<h2>Drag and Drop demo</h2>
<div id="div1"
(drop)="drop($event)"
(dragover)="allowDrop($event)">

<img
src="https://images.pexels.com/photos/658687/pexels-photo-658687.jpeg?auto=compress&cs=tinysrgb&h=350"
draggable="true"
(dragstart)="drag($event)"
id="drag1"
width="88"
height="31">
</div>

<div id="div2"
(drop)="drop($event)"
(dragover)="allowDrop($event)">
</div>


drag.component.ts:



import { Component } from '@angular/core';

@Component({
selector: 'drag-root',
templateUrl: './drag.component.html',
styleUrls: ['./drag.component.css']
})
export class AppComponent {

drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}

allowDrop(ev) {
ev.preventDefault();
}

drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
}


drag.component.css:



#div1, #div2 {
float: left;
width: 100px;
height: 35px;
margin: 10px;
padding: 10px;
border: 1px solid black;
}


Stackblitz example






share|improve this answer

































    5














    <div (dragover)="onDragOver($event)" (dragleave)="onDragLeave($event)" (drop)="onDrop($event)">




    In your Component



    onDrop(event: any) {
    event.preventDefault();
    event.stopPropagation();
    // your code goes here after droping files or any
    }

    onDragOver(evt) {
    evt.preventDefault();
    evt.stopPropagation();
    }

    onDragLeave(evt) {
    evt.preventDefault();
    evt.stopPropagation();
    }





    share|improve this answer
























    • The dragLeave fires, but I am not sure how to use it. The drop event doesn't fire at all.

      – Sumchans
      Dec 26 '17 at 17:27











    • For you to deal with drop events, you have to add event.preventDefault() in dragover handler

      – Pradeep
      May 23 '18 at 15:59



















    1














    To use drag and drop in angular 4 application you can use npm module "ngx-uploader".



    You will find the integration step from below link:



    https://www.npmjs.com/package/ngx-uploader



    All the imports parameter and classes you can take from the above link.



    Here is my code for angular:



    if (output.type === 'allAddedToQueue') { // when all files added in queue
    // uncomment this if you want to auto upload files when added
    const event: UploadInput = {
    type: 'uploadAll',
    url: API_BASE +'/api/uploads',

    method: 'POST',
    data:{total_files: this.files.length.toString()}
    };
    this.uploadInput.emit(event);
    } else if (output.type === 'addedToQueue' && typeof output.file !== 'undefined') { // add file to array when added
    this.files.push(output.file);
    } else if (output.type === 'uploading' && typeof output.file !== 'undefined') {
    // update current data in files array for uploading file
    const index = this.files.findIndex(file => typeof output.file !== 'undefined' && file.id === output.file.id);
    this.files[index] = output.file;

    } else if (output.type === 'removed') {
    // remove file from array when removed
    this.files = this.files.filter((file: UploadFile) => file !== output.file);
    } else if (output.type === 'dragOver') {
    this.dragOver = true;
    } else if (output.type === 'dragOut') {
    this.dragOver = false;
    } else if (output.type === 'drop') {
    this.dragOver = false;
    }else if (output.type === 'done') {

    if (output.file.response.status == 200) {
    var uploaded_files = output.file.response.data;
    this.propertyImage.push(uploaded_files);
    }
    else {
    this.msgs = ;
    this.msgs.push({ severity: 'error', summary: 'Error Message', detail: 'unable to upload images' });
    }


    In the above code for output === done, you will get response from server side (In my case nodejs)



    Below you can find the code for backend:



    var formidable = require('formidable'),
    http = require('http'),
    util = require('util');

    var form = new formidable.IncomingForm();

    var src = './public/images/properties';
    var dst_small = './public/images/properties/small'
    var dst_medium = './public/images/properties/medium'
    var validImage = false;
    form.keepExtensions = true; //keep file extension
    form.uploadDir = src;
    form.onPart = function (part) {
    if (!part.filename || part.filename.match(/.(jpg|jpeg|png)$/i)) {
    validImage = true;
    this.handlePart(part);
    }

    else {
    validImage = false;
    return res.json({ status: 404, msg: part.filename + ' is not allowed.' });

    }
    }
    form.parse(req, function (err, fields, files) {
    if (validImage) {

    var image = files.file.path.split("/")[3];
    var name = files.file.path.split("/")[3];


    easyimg.rescrop({
    src: files.file.path, dst: dst_small + '/' + files.file.path.split('/')[3],
    width: 100, height: 100,
    cropwidth: 100, cropheight: 100,
    x: 0, y: 0
    }).then(
    function (image) {
    // console.log('Resized and cropped: ' + image.width + ' x ' + image.height);
    },
    function (err) {
    // console.log(err);
    }
    );


    // for largeImage
    easyimg.rescrop({
    src: files.file.path, dst: dst_medium + '/' + files.file.path.split('/')[3],
    width: 300, height: 300,
    cropwidth: 300, cropheight: 300,
    x: 0, y: 0
    }).then(
    function (image) {
    // console.log('Resized and cropped: ' + image.width + ' x ' + image.height);
    return res.json({ status: 200, msg: 'Uploaded images', data: image });

    },
    function (err) {
    console.log(err);
    }
    );
    } else {
    return res.json({ status: 500, msg: constant.message.error_profile_pic_type });
    }
    });


    Please change your image path according to your file path. I have used this code and it worked for me.



    Hope the above code will help for you.



    Thanks !!






    share|improve this answer































      1














      Simple but most powerful package



      supports angular version >= 4.x



      for documentation



      for demo



      How to use it?



      Install



      // if you use npm
      npm install angular2-draggable

      // or if you use yarn
      yarn add angular2-draggable


      Import



      import { AngularDraggableModule } from 'angular2-draggable';

      @NgModule({
      imports: [
      ...,
      AngularDraggableModule
      ],
      })
      export class AppModule { }


      and finally use



      // Basic Usage
      <div ngDraggable>Drag Me!</div>





      share|improve this answer


























      • Thanks man. Sure will use it.

        – Sumchans
        Feb 26 '18 at 23:30











      • this is true, it is very simple and very powerful.

        – argoden
        Aug 16 '18 at 21:40



















      1














      Here is a solution on Angular 7:



      Material (https://material.angular.io/) explains it perfectly (you have to take version >= 7.1). Here is a link to API.



      First, import "DragAndDrop" module in your modules:



      import {DragDropModule} from '@angular/cdk/drag-drop';


      Then you just have to add "cdkDrag" directive to your HTML element:



      <div class="example-box" cdkDrag>
      Drag me around
      </div>


      Stackblitz (from material):
      here



      It's really easy to use and there are interesting options if you need to do a more specific drag and drop (for example with a position locking) !






      share|improve this answer


























      • Wow that's good. Thank you. Will check it out.

        – Sumchans
        Nov 21 '18 at 15:12



















      0














      Use drop event. This will fire only when you drop a file.






      share|improve this answer



















      • 1





        I did the use the drop event, it doesn't fire anything when I drop.

        – Sumchans
        Dec 26 '17 at 8:08



















      0














      This is this the way I got it working.
      preventDefault() functions throws error, changed it for return false which worked fine. Thanks guys for the prompt responses.



       drag(channel) {
      console.log(channel);
      }
      onDragOver(channel: any) {
      console.log("Drag Over");
      return false;
      }
      onDrop(e:any) {
      console.log("Drop");
      }





      share|improve this answer























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f47975237%2fhtml-5-drag-drop-with-angular-4%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        7 Answers
        7






        active

        oldest

        votes








        7 Answers
        7






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        9














        I made it without any other module in Angular 2/4/5/6, You can also make it by using below code:



        drag.component.html:



        <h2>Drag and Drop demo</h2>
        <div id="div1"
        (drop)="drop($event)"
        (dragover)="allowDrop($event)">

        <img
        src="https://images.pexels.com/photos/658687/pexels-photo-658687.jpeg?auto=compress&cs=tinysrgb&h=350"
        draggable="true"
        (dragstart)="drag($event)"
        id="drag1"
        width="88"
        height="31">
        </div>

        <div id="div2"
        (drop)="drop($event)"
        (dragover)="allowDrop($event)">
        </div>


        drag.component.ts:



        import { Component } from '@angular/core';

        @Component({
        selector: 'drag-root',
        templateUrl: './drag.component.html',
        styleUrls: ['./drag.component.css']
        })
        export class AppComponent {

        drop(ev) {
        ev.preventDefault();
        var data = ev.dataTransfer.getData("text");
        ev.target.appendChild(document.getElementById(data));
        }

        allowDrop(ev) {
        ev.preventDefault();
        }

        drag(ev) {
        ev.dataTransfer.setData("text", ev.target.id);
        }
        }


        drag.component.css:



        #div1, #div2 {
        float: left;
        width: 100px;
        height: 35px;
        margin: 10px;
        padding: 10px;
        border: 1px solid black;
        }


        Stackblitz example






        share|improve this answer






























          9














          I made it without any other module in Angular 2/4/5/6, You can also make it by using below code:



          drag.component.html:



          <h2>Drag and Drop demo</h2>
          <div id="div1"
          (drop)="drop($event)"
          (dragover)="allowDrop($event)">

          <img
          src="https://images.pexels.com/photos/658687/pexels-photo-658687.jpeg?auto=compress&cs=tinysrgb&h=350"
          draggable="true"
          (dragstart)="drag($event)"
          id="drag1"
          width="88"
          height="31">
          </div>

          <div id="div2"
          (drop)="drop($event)"
          (dragover)="allowDrop($event)">
          </div>


          drag.component.ts:



          import { Component } from '@angular/core';

          @Component({
          selector: 'drag-root',
          templateUrl: './drag.component.html',
          styleUrls: ['./drag.component.css']
          })
          export class AppComponent {

          drop(ev) {
          ev.preventDefault();
          var data = ev.dataTransfer.getData("text");
          ev.target.appendChild(document.getElementById(data));
          }

          allowDrop(ev) {
          ev.preventDefault();
          }

          drag(ev) {
          ev.dataTransfer.setData("text", ev.target.id);
          }
          }


          drag.component.css:



          #div1, #div2 {
          float: left;
          width: 100px;
          height: 35px;
          margin: 10px;
          padding: 10px;
          border: 1px solid black;
          }


          Stackblitz example






          share|improve this answer




























            9












            9








            9







            I made it without any other module in Angular 2/4/5/6, You can also make it by using below code:



            drag.component.html:



            <h2>Drag and Drop demo</h2>
            <div id="div1"
            (drop)="drop($event)"
            (dragover)="allowDrop($event)">

            <img
            src="https://images.pexels.com/photos/658687/pexels-photo-658687.jpeg?auto=compress&cs=tinysrgb&h=350"
            draggable="true"
            (dragstart)="drag($event)"
            id="drag1"
            width="88"
            height="31">
            </div>

            <div id="div2"
            (drop)="drop($event)"
            (dragover)="allowDrop($event)">
            </div>


            drag.component.ts:



            import { Component } from '@angular/core';

            @Component({
            selector: 'drag-root',
            templateUrl: './drag.component.html',
            styleUrls: ['./drag.component.css']
            })
            export class AppComponent {

            drop(ev) {
            ev.preventDefault();
            var data = ev.dataTransfer.getData("text");
            ev.target.appendChild(document.getElementById(data));
            }

            allowDrop(ev) {
            ev.preventDefault();
            }

            drag(ev) {
            ev.dataTransfer.setData("text", ev.target.id);
            }
            }


            drag.component.css:



            #div1, #div2 {
            float: left;
            width: 100px;
            height: 35px;
            margin: 10px;
            padding: 10px;
            border: 1px solid black;
            }


            Stackblitz example






            share|improve this answer















            I made it without any other module in Angular 2/4/5/6, You can also make it by using below code:



            drag.component.html:



            <h2>Drag and Drop demo</h2>
            <div id="div1"
            (drop)="drop($event)"
            (dragover)="allowDrop($event)">

            <img
            src="https://images.pexels.com/photos/658687/pexels-photo-658687.jpeg?auto=compress&cs=tinysrgb&h=350"
            draggable="true"
            (dragstart)="drag($event)"
            id="drag1"
            width="88"
            height="31">
            </div>

            <div id="div2"
            (drop)="drop($event)"
            (dragover)="allowDrop($event)">
            </div>


            drag.component.ts:



            import { Component } from '@angular/core';

            @Component({
            selector: 'drag-root',
            templateUrl: './drag.component.html',
            styleUrls: ['./drag.component.css']
            })
            export class AppComponent {

            drop(ev) {
            ev.preventDefault();
            var data = ev.dataTransfer.getData("text");
            ev.target.appendChild(document.getElementById(data));
            }

            allowDrop(ev) {
            ev.preventDefault();
            }

            drag(ev) {
            ev.dataTransfer.setData("text", ev.target.id);
            }
            }


            drag.component.css:



            #div1, #div2 {
            float: left;
            width: 100px;
            height: 35px;
            margin: 10px;
            padding: 10px;
            border: 1px solid black;
            }


            Stackblitz example







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 25 '18 at 6:14









            לבני מלכה

            9,7441726




            9,7441726










            answered Jun 25 '18 at 15:09









            Shubham VermaShubham Verma

            2,52622550




            2,52622550

























                5














                <div (dragover)="onDragOver($event)" (dragleave)="onDragLeave($event)" (drop)="onDrop($event)">




                In your Component



                onDrop(event: any) {
                event.preventDefault();
                event.stopPropagation();
                // your code goes here after droping files or any
                }

                onDragOver(evt) {
                evt.preventDefault();
                evt.stopPropagation();
                }

                onDragLeave(evt) {
                evt.preventDefault();
                evt.stopPropagation();
                }





                share|improve this answer
























                • The dragLeave fires, but I am not sure how to use it. The drop event doesn't fire at all.

                  – Sumchans
                  Dec 26 '17 at 17:27











                • For you to deal with drop events, you have to add event.preventDefault() in dragover handler

                  – Pradeep
                  May 23 '18 at 15:59
















                5














                <div (dragover)="onDragOver($event)" (dragleave)="onDragLeave($event)" (drop)="onDrop($event)">




                In your Component



                onDrop(event: any) {
                event.preventDefault();
                event.stopPropagation();
                // your code goes here after droping files or any
                }

                onDragOver(evt) {
                evt.preventDefault();
                evt.stopPropagation();
                }

                onDragLeave(evt) {
                evt.preventDefault();
                evt.stopPropagation();
                }





                share|improve this answer
























                • The dragLeave fires, but I am not sure how to use it. The drop event doesn't fire at all.

                  – Sumchans
                  Dec 26 '17 at 17:27











                • For you to deal with drop events, you have to add event.preventDefault() in dragover handler

                  – Pradeep
                  May 23 '18 at 15:59














                5












                5








                5







                <div (dragover)="onDragOver($event)" (dragleave)="onDragLeave($event)" (drop)="onDrop($event)">




                In your Component



                onDrop(event: any) {
                event.preventDefault();
                event.stopPropagation();
                // your code goes here after droping files or any
                }

                onDragOver(evt) {
                evt.preventDefault();
                evt.stopPropagation();
                }

                onDragLeave(evt) {
                evt.preventDefault();
                evt.stopPropagation();
                }





                share|improve this answer













                <div (dragover)="onDragOver($event)" (dragleave)="onDragLeave($event)" (drop)="onDrop($event)">




                In your Component



                onDrop(event: any) {
                event.preventDefault();
                event.stopPropagation();
                // your code goes here after droping files or any
                }

                onDragOver(evt) {
                evt.preventDefault();
                evt.stopPropagation();
                }

                onDragLeave(evt) {
                evt.preventDefault();
                evt.stopPropagation();
                }






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Dec 26 '17 at 12:48









                Phani KumarPhani Kumar

                1554




                1554













                • The dragLeave fires, but I am not sure how to use it. The drop event doesn't fire at all.

                  – Sumchans
                  Dec 26 '17 at 17:27











                • For you to deal with drop events, you have to add event.preventDefault() in dragover handler

                  – Pradeep
                  May 23 '18 at 15:59



















                • The dragLeave fires, but I am not sure how to use it. The drop event doesn't fire at all.

                  – Sumchans
                  Dec 26 '17 at 17:27











                • For you to deal with drop events, you have to add event.preventDefault() in dragover handler

                  – Pradeep
                  May 23 '18 at 15:59

















                The dragLeave fires, but I am not sure how to use it. The drop event doesn't fire at all.

                – Sumchans
                Dec 26 '17 at 17:27





                The dragLeave fires, but I am not sure how to use it. The drop event doesn't fire at all.

                – Sumchans
                Dec 26 '17 at 17:27













                For you to deal with drop events, you have to add event.preventDefault() in dragover handler

                – Pradeep
                May 23 '18 at 15:59





                For you to deal with drop events, you have to add event.preventDefault() in dragover handler

                – Pradeep
                May 23 '18 at 15:59











                1














                To use drag and drop in angular 4 application you can use npm module "ngx-uploader".



                You will find the integration step from below link:



                https://www.npmjs.com/package/ngx-uploader



                All the imports parameter and classes you can take from the above link.



                Here is my code for angular:



                if (output.type === 'allAddedToQueue') { // when all files added in queue
                // uncomment this if you want to auto upload files when added
                const event: UploadInput = {
                type: 'uploadAll',
                url: API_BASE +'/api/uploads',

                method: 'POST',
                data:{total_files: this.files.length.toString()}
                };
                this.uploadInput.emit(event);
                } else if (output.type === 'addedToQueue' && typeof output.file !== 'undefined') { // add file to array when added
                this.files.push(output.file);
                } else if (output.type === 'uploading' && typeof output.file !== 'undefined') {
                // update current data in files array for uploading file
                const index = this.files.findIndex(file => typeof output.file !== 'undefined' && file.id === output.file.id);
                this.files[index] = output.file;

                } else if (output.type === 'removed') {
                // remove file from array when removed
                this.files = this.files.filter((file: UploadFile) => file !== output.file);
                } else if (output.type === 'dragOver') {
                this.dragOver = true;
                } else if (output.type === 'dragOut') {
                this.dragOver = false;
                } else if (output.type === 'drop') {
                this.dragOver = false;
                }else if (output.type === 'done') {

                if (output.file.response.status == 200) {
                var uploaded_files = output.file.response.data;
                this.propertyImage.push(uploaded_files);
                }
                else {
                this.msgs = ;
                this.msgs.push({ severity: 'error', summary: 'Error Message', detail: 'unable to upload images' });
                }


                In the above code for output === done, you will get response from server side (In my case nodejs)



                Below you can find the code for backend:



                var formidable = require('formidable'),
                http = require('http'),
                util = require('util');

                var form = new formidable.IncomingForm();

                var src = './public/images/properties';
                var dst_small = './public/images/properties/small'
                var dst_medium = './public/images/properties/medium'
                var validImage = false;
                form.keepExtensions = true; //keep file extension
                form.uploadDir = src;
                form.onPart = function (part) {
                if (!part.filename || part.filename.match(/.(jpg|jpeg|png)$/i)) {
                validImage = true;
                this.handlePart(part);
                }

                else {
                validImage = false;
                return res.json({ status: 404, msg: part.filename + ' is not allowed.' });

                }
                }
                form.parse(req, function (err, fields, files) {
                if (validImage) {

                var image = files.file.path.split("/")[3];
                var name = files.file.path.split("/")[3];


                easyimg.rescrop({
                src: files.file.path, dst: dst_small + '/' + files.file.path.split('/')[3],
                width: 100, height: 100,
                cropwidth: 100, cropheight: 100,
                x: 0, y: 0
                }).then(
                function (image) {
                // console.log('Resized and cropped: ' + image.width + ' x ' + image.height);
                },
                function (err) {
                // console.log(err);
                }
                );


                // for largeImage
                easyimg.rescrop({
                src: files.file.path, dst: dst_medium + '/' + files.file.path.split('/')[3],
                width: 300, height: 300,
                cropwidth: 300, cropheight: 300,
                x: 0, y: 0
                }).then(
                function (image) {
                // console.log('Resized and cropped: ' + image.width + ' x ' + image.height);
                return res.json({ status: 200, msg: 'Uploaded images', data: image });

                },
                function (err) {
                console.log(err);
                }
                );
                } else {
                return res.json({ status: 500, msg: constant.message.error_profile_pic_type });
                }
                });


                Please change your image path according to your file path. I have used this code and it worked for me.



                Hope the above code will help for you.



                Thanks !!






                share|improve this answer




























                  1














                  To use drag and drop in angular 4 application you can use npm module "ngx-uploader".



                  You will find the integration step from below link:



                  https://www.npmjs.com/package/ngx-uploader



                  All the imports parameter and classes you can take from the above link.



                  Here is my code for angular:



                  if (output.type === 'allAddedToQueue') { // when all files added in queue
                  // uncomment this if you want to auto upload files when added
                  const event: UploadInput = {
                  type: 'uploadAll',
                  url: API_BASE +'/api/uploads',

                  method: 'POST',
                  data:{total_files: this.files.length.toString()}
                  };
                  this.uploadInput.emit(event);
                  } else if (output.type === 'addedToQueue' && typeof output.file !== 'undefined') { // add file to array when added
                  this.files.push(output.file);
                  } else if (output.type === 'uploading' && typeof output.file !== 'undefined') {
                  // update current data in files array for uploading file
                  const index = this.files.findIndex(file => typeof output.file !== 'undefined' && file.id === output.file.id);
                  this.files[index] = output.file;

                  } else if (output.type === 'removed') {
                  // remove file from array when removed
                  this.files = this.files.filter((file: UploadFile) => file !== output.file);
                  } else if (output.type === 'dragOver') {
                  this.dragOver = true;
                  } else if (output.type === 'dragOut') {
                  this.dragOver = false;
                  } else if (output.type === 'drop') {
                  this.dragOver = false;
                  }else if (output.type === 'done') {

                  if (output.file.response.status == 200) {
                  var uploaded_files = output.file.response.data;
                  this.propertyImage.push(uploaded_files);
                  }
                  else {
                  this.msgs = ;
                  this.msgs.push({ severity: 'error', summary: 'Error Message', detail: 'unable to upload images' });
                  }


                  In the above code for output === done, you will get response from server side (In my case nodejs)



                  Below you can find the code for backend:



                  var formidable = require('formidable'),
                  http = require('http'),
                  util = require('util');

                  var form = new formidable.IncomingForm();

                  var src = './public/images/properties';
                  var dst_small = './public/images/properties/small'
                  var dst_medium = './public/images/properties/medium'
                  var validImage = false;
                  form.keepExtensions = true; //keep file extension
                  form.uploadDir = src;
                  form.onPart = function (part) {
                  if (!part.filename || part.filename.match(/.(jpg|jpeg|png)$/i)) {
                  validImage = true;
                  this.handlePart(part);
                  }

                  else {
                  validImage = false;
                  return res.json({ status: 404, msg: part.filename + ' is not allowed.' });

                  }
                  }
                  form.parse(req, function (err, fields, files) {
                  if (validImage) {

                  var image = files.file.path.split("/")[3];
                  var name = files.file.path.split("/")[3];


                  easyimg.rescrop({
                  src: files.file.path, dst: dst_small + '/' + files.file.path.split('/')[3],
                  width: 100, height: 100,
                  cropwidth: 100, cropheight: 100,
                  x: 0, y: 0
                  }).then(
                  function (image) {
                  // console.log('Resized and cropped: ' + image.width + ' x ' + image.height);
                  },
                  function (err) {
                  // console.log(err);
                  }
                  );


                  // for largeImage
                  easyimg.rescrop({
                  src: files.file.path, dst: dst_medium + '/' + files.file.path.split('/')[3],
                  width: 300, height: 300,
                  cropwidth: 300, cropheight: 300,
                  x: 0, y: 0
                  }).then(
                  function (image) {
                  // console.log('Resized and cropped: ' + image.width + ' x ' + image.height);
                  return res.json({ status: 200, msg: 'Uploaded images', data: image });

                  },
                  function (err) {
                  console.log(err);
                  }
                  );
                  } else {
                  return res.json({ status: 500, msg: constant.message.error_profile_pic_type });
                  }
                  });


                  Please change your image path according to your file path. I have used this code and it worked for me.



                  Hope the above code will help for you.



                  Thanks !!






                  share|improve this answer


























                    1












                    1








                    1







                    To use drag and drop in angular 4 application you can use npm module "ngx-uploader".



                    You will find the integration step from below link:



                    https://www.npmjs.com/package/ngx-uploader



                    All the imports parameter and classes you can take from the above link.



                    Here is my code for angular:



                    if (output.type === 'allAddedToQueue') { // when all files added in queue
                    // uncomment this if you want to auto upload files when added
                    const event: UploadInput = {
                    type: 'uploadAll',
                    url: API_BASE +'/api/uploads',

                    method: 'POST',
                    data:{total_files: this.files.length.toString()}
                    };
                    this.uploadInput.emit(event);
                    } else if (output.type === 'addedToQueue' && typeof output.file !== 'undefined') { // add file to array when added
                    this.files.push(output.file);
                    } else if (output.type === 'uploading' && typeof output.file !== 'undefined') {
                    // update current data in files array for uploading file
                    const index = this.files.findIndex(file => typeof output.file !== 'undefined' && file.id === output.file.id);
                    this.files[index] = output.file;

                    } else if (output.type === 'removed') {
                    // remove file from array when removed
                    this.files = this.files.filter((file: UploadFile) => file !== output.file);
                    } else if (output.type === 'dragOver') {
                    this.dragOver = true;
                    } else if (output.type === 'dragOut') {
                    this.dragOver = false;
                    } else if (output.type === 'drop') {
                    this.dragOver = false;
                    }else if (output.type === 'done') {

                    if (output.file.response.status == 200) {
                    var uploaded_files = output.file.response.data;
                    this.propertyImage.push(uploaded_files);
                    }
                    else {
                    this.msgs = ;
                    this.msgs.push({ severity: 'error', summary: 'Error Message', detail: 'unable to upload images' });
                    }


                    In the above code for output === done, you will get response from server side (In my case nodejs)



                    Below you can find the code for backend:



                    var formidable = require('formidable'),
                    http = require('http'),
                    util = require('util');

                    var form = new formidable.IncomingForm();

                    var src = './public/images/properties';
                    var dst_small = './public/images/properties/small'
                    var dst_medium = './public/images/properties/medium'
                    var validImage = false;
                    form.keepExtensions = true; //keep file extension
                    form.uploadDir = src;
                    form.onPart = function (part) {
                    if (!part.filename || part.filename.match(/.(jpg|jpeg|png)$/i)) {
                    validImage = true;
                    this.handlePart(part);
                    }

                    else {
                    validImage = false;
                    return res.json({ status: 404, msg: part.filename + ' is not allowed.' });

                    }
                    }
                    form.parse(req, function (err, fields, files) {
                    if (validImage) {

                    var image = files.file.path.split("/")[3];
                    var name = files.file.path.split("/")[3];


                    easyimg.rescrop({
                    src: files.file.path, dst: dst_small + '/' + files.file.path.split('/')[3],
                    width: 100, height: 100,
                    cropwidth: 100, cropheight: 100,
                    x: 0, y: 0
                    }).then(
                    function (image) {
                    // console.log('Resized and cropped: ' + image.width + ' x ' + image.height);
                    },
                    function (err) {
                    // console.log(err);
                    }
                    );


                    // for largeImage
                    easyimg.rescrop({
                    src: files.file.path, dst: dst_medium + '/' + files.file.path.split('/')[3],
                    width: 300, height: 300,
                    cropwidth: 300, cropheight: 300,
                    x: 0, y: 0
                    }).then(
                    function (image) {
                    // console.log('Resized and cropped: ' + image.width + ' x ' + image.height);
                    return res.json({ status: 200, msg: 'Uploaded images', data: image });

                    },
                    function (err) {
                    console.log(err);
                    }
                    );
                    } else {
                    return res.json({ status: 500, msg: constant.message.error_profile_pic_type });
                    }
                    });


                    Please change your image path according to your file path. I have used this code and it worked for me.



                    Hope the above code will help for you.



                    Thanks !!






                    share|improve this answer













                    To use drag and drop in angular 4 application you can use npm module "ngx-uploader".



                    You will find the integration step from below link:



                    https://www.npmjs.com/package/ngx-uploader



                    All the imports parameter and classes you can take from the above link.



                    Here is my code for angular:



                    if (output.type === 'allAddedToQueue') { // when all files added in queue
                    // uncomment this if you want to auto upload files when added
                    const event: UploadInput = {
                    type: 'uploadAll',
                    url: API_BASE +'/api/uploads',

                    method: 'POST',
                    data:{total_files: this.files.length.toString()}
                    };
                    this.uploadInput.emit(event);
                    } else if (output.type === 'addedToQueue' && typeof output.file !== 'undefined') { // add file to array when added
                    this.files.push(output.file);
                    } else if (output.type === 'uploading' && typeof output.file !== 'undefined') {
                    // update current data in files array for uploading file
                    const index = this.files.findIndex(file => typeof output.file !== 'undefined' && file.id === output.file.id);
                    this.files[index] = output.file;

                    } else if (output.type === 'removed') {
                    // remove file from array when removed
                    this.files = this.files.filter((file: UploadFile) => file !== output.file);
                    } else if (output.type === 'dragOver') {
                    this.dragOver = true;
                    } else if (output.type === 'dragOut') {
                    this.dragOver = false;
                    } else if (output.type === 'drop') {
                    this.dragOver = false;
                    }else if (output.type === 'done') {

                    if (output.file.response.status == 200) {
                    var uploaded_files = output.file.response.data;
                    this.propertyImage.push(uploaded_files);
                    }
                    else {
                    this.msgs = ;
                    this.msgs.push({ severity: 'error', summary: 'Error Message', detail: 'unable to upload images' });
                    }


                    In the above code for output === done, you will get response from server side (In my case nodejs)



                    Below you can find the code for backend:



                    var formidable = require('formidable'),
                    http = require('http'),
                    util = require('util');

                    var form = new formidable.IncomingForm();

                    var src = './public/images/properties';
                    var dst_small = './public/images/properties/small'
                    var dst_medium = './public/images/properties/medium'
                    var validImage = false;
                    form.keepExtensions = true; //keep file extension
                    form.uploadDir = src;
                    form.onPart = function (part) {
                    if (!part.filename || part.filename.match(/.(jpg|jpeg|png)$/i)) {
                    validImage = true;
                    this.handlePart(part);
                    }

                    else {
                    validImage = false;
                    return res.json({ status: 404, msg: part.filename + ' is not allowed.' });

                    }
                    }
                    form.parse(req, function (err, fields, files) {
                    if (validImage) {

                    var image = files.file.path.split("/")[3];
                    var name = files.file.path.split("/")[3];


                    easyimg.rescrop({
                    src: files.file.path, dst: dst_small + '/' + files.file.path.split('/')[3],
                    width: 100, height: 100,
                    cropwidth: 100, cropheight: 100,
                    x: 0, y: 0
                    }).then(
                    function (image) {
                    // console.log('Resized and cropped: ' + image.width + ' x ' + image.height);
                    },
                    function (err) {
                    // console.log(err);
                    }
                    );


                    // for largeImage
                    easyimg.rescrop({
                    src: files.file.path, dst: dst_medium + '/' + files.file.path.split('/')[3],
                    width: 300, height: 300,
                    cropwidth: 300, cropheight: 300,
                    x: 0, y: 0
                    }).then(
                    function (image) {
                    // console.log('Resized and cropped: ' + image.width + ' x ' + image.height);
                    return res.json({ status: 200, msg: 'Uploaded images', data: image });

                    },
                    function (err) {
                    console.log(err);
                    }
                    );
                    } else {
                    return res.json({ status: 500, msg: constant.message.error_profile_pic_type });
                    }
                    });


                    Please change your image path according to your file path. I have used this code and it worked for me.



                    Hope the above code will help for you.



                    Thanks !!







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 6 '18 at 5:44









                    RsonaRsona

                    113




                    113























                        1














                        Simple but most powerful package



                        supports angular version >= 4.x



                        for documentation



                        for demo



                        How to use it?



                        Install



                        // if you use npm
                        npm install angular2-draggable

                        // or if you use yarn
                        yarn add angular2-draggable


                        Import



                        import { AngularDraggableModule } from 'angular2-draggable';

                        @NgModule({
                        imports: [
                        ...,
                        AngularDraggableModule
                        ],
                        })
                        export class AppModule { }


                        and finally use



                        // Basic Usage
                        <div ngDraggable>Drag Me!</div>





                        share|improve this answer


























                        • Thanks man. Sure will use it.

                          – Sumchans
                          Feb 26 '18 at 23:30











                        • this is true, it is very simple and very powerful.

                          – argoden
                          Aug 16 '18 at 21:40
















                        1














                        Simple but most powerful package



                        supports angular version >= 4.x



                        for documentation



                        for demo



                        How to use it?



                        Install



                        // if you use npm
                        npm install angular2-draggable

                        // or if you use yarn
                        yarn add angular2-draggable


                        Import



                        import { AngularDraggableModule } from 'angular2-draggable';

                        @NgModule({
                        imports: [
                        ...,
                        AngularDraggableModule
                        ],
                        })
                        export class AppModule { }


                        and finally use



                        // Basic Usage
                        <div ngDraggable>Drag Me!</div>





                        share|improve this answer


























                        • Thanks man. Sure will use it.

                          – Sumchans
                          Feb 26 '18 at 23:30











                        • this is true, it is very simple and very powerful.

                          – argoden
                          Aug 16 '18 at 21:40














                        1












                        1








                        1







                        Simple but most powerful package



                        supports angular version >= 4.x



                        for documentation



                        for demo



                        How to use it?



                        Install



                        // if you use npm
                        npm install angular2-draggable

                        // or if you use yarn
                        yarn add angular2-draggable


                        Import



                        import { AngularDraggableModule } from 'angular2-draggable';

                        @NgModule({
                        imports: [
                        ...,
                        AngularDraggableModule
                        ],
                        })
                        export class AppModule { }


                        and finally use



                        // Basic Usage
                        <div ngDraggable>Drag Me!</div>





                        share|improve this answer















                        Simple but most powerful package



                        supports angular version >= 4.x



                        for documentation



                        for demo



                        How to use it?



                        Install



                        // if you use npm
                        npm install angular2-draggable

                        // or if you use yarn
                        yarn add angular2-draggable


                        Import



                        import { AngularDraggableModule } from 'angular2-draggable';

                        @NgModule({
                        imports: [
                        ...,
                        AngularDraggableModule
                        ],
                        })
                        export class AppModule { }


                        and finally use



                        // Basic Usage
                        <div ngDraggable>Drag Me!</div>






                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Jun 23 '18 at 11:00

























                        answered Feb 26 '18 at 7:58









                        WasiFWasiF

                        2,1742234




                        2,1742234













                        • Thanks man. Sure will use it.

                          – Sumchans
                          Feb 26 '18 at 23:30











                        • this is true, it is very simple and very powerful.

                          – argoden
                          Aug 16 '18 at 21:40



















                        • Thanks man. Sure will use it.

                          – Sumchans
                          Feb 26 '18 at 23:30











                        • this is true, it is very simple and very powerful.

                          – argoden
                          Aug 16 '18 at 21:40

















                        Thanks man. Sure will use it.

                        – Sumchans
                        Feb 26 '18 at 23:30





                        Thanks man. Sure will use it.

                        – Sumchans
                        Feb 26 '18 at 23:30













                        this is true, it is very simple and very powerful.

                        – argoden
                        Aug 16 '18 at 21:40





                        this is true, it is very simple and very powerful.

                        – argoden
                        Aug 16 '18 at 21:40











                        1














                        Here is a solution on Angular 7:



                        Material (https://material.angular.io/) explains it perfectly (you have to take version >= 7.1). Here is a link to API.



                        First, import "DragAndDrop" module in your modules:



                        import {DragDropModule} from '@angular/cdk/drag-drop';


                        Then you just have to add "cdkDrag" directive to your HTML element:



                        <div class="example-box" cdkDrag>
                        Drag me around
                        </div>


                        Stackblitz (from material):
                        here



                        It's really easy to use and there are interesting options if you need to do a more specific drag and drop (for example with a position locking) !






                        share|improve this answer


























                        • Wow that's good. Thank you. Will check it out.

                          – Sumchans
                          Nov 21 '18 at 15:12
















                        1














                        Here is a solution on Angular 7:



                        Material (https://material.angular.io/) explains it perfectly (you have to take version >= 7.1). Here is a link to API.



                        First, import "DragAndDrop" module in your modules:



                        import {DragDropModule} from '@angular/cdk/drag-drop';


                        Then you just have to add "cdkDrag" directive to your HTML element:



                        <div class="example-box" cdkDrag>
                        Drag me around
                        </div>


                        Stackblitz (from material):
                        here



                        It's really easy to use and there are interesting options if you need to do a more specific drag and drop (for example with a position locking) !






                        share|improve this answer


























                        • Wow that's good. Thank you. Will check it out.

                          – Sumchans
                          Nov 21 '18 at 15:12














                        1












                        1








                        1







                        Here is a solution on Angular 7:



                        Material (https://material.angular.io/) explains it perfectly (you have to take version >= 7.1). Here is a link to API.



                        First, import "DragAndDrop" module in your modules:



                        import {DragDropModule} from '@angular/cdk/drag-drop';


                        Then you just have to add "cdkDrag" directive to your HTML element:



                        <div class="example-box" cdkDrag>
                        Drag me around
                        </div>


                        Stackblitz (from material):
                        here



                        It's really easy to use and there are interesting options if you need to do a more specific drag and drop (for example with a position locking) !






                        share|improve this answer















                        Here is a solution on Angular 7:



                        Material (https://material.angular.io/) explains it perfectly (you have to take version >= 7.1). Here is a link to API.



                        First, import "DragAndDrop" module in your modules:



                        import {DragDropModule} from '@angular/cdk/drag-drop';


                        Then you just have to add "cdkDrag" directive to your HTML element:



                        <div class="example-box" cdkDrag>
                        Drag me around
                        </div>


                        Stackblitz (from material):
                        here



                        It's really easy to use and there are interesting options if you need to do a more specific drag and drop (for example with a position locking) !







                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Nov 22 '18 at 8:12

























                        answered Nov 21 '18 at 10:55









                        CurseCurse

                        1531111




                        1531111













                        • Wow that's good. Thank you. Will check it out.

                          – Sumchans
                          Nov 21 '18 at 15:12



















                        • Wow that's good. Thank you. Will check it out.

                          – Sumchans
                          Nov 21 '18 at 15:12

















                        Wow that's good. Thank you. Will check it out.

                        – Sumchans
                        Nov 21 '18 at 15:12





                        Wow that's good. Thank you. Will check it out.

                        – Sumchans
                        Nov 21 '18 at 15:12











                        0














                        Use drop event. This will fire only when you drop a file.






                        share|improve this answer



















                        • 1





                          I did the use the drop event, it doesn't fire anything when I drop.

                          – Sumchans
                          Dec 26 '17 at 8:08
















                        0














                        Use drop event. This will fire only when you drop a file.






                        share|improve this answer



















                        • 1





                          I did the use the drop event, it doesn't fire anything when I drop.

                          – Sumchans
                          Dec 26 '17 at 8:08














                        0












                        0








                        0







                        Use drop event. This will fire only when you drop a file.






                        share|improve this answer













                        Use drop event. This will fire only when you drop a file.







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Dec 26 '17 at 7:50









                        sachin sachin

                        442




                        442








                        • 1





                          I did the use the drop event, it doesn't fire anything when I drop.

                          – Sumchans
                          Dec 26 '17 at 8:08














                        • 1





                          I did the use the drop event, it doesn't fire anything when I drop.

                          – Sumchans
                          Dec 26 '17 at 8:08








                        1




                        1





                        I did the use the drop event, it doesn't fire anything when I drop.

                        – Sumchans
                        Dec 26 '17 at 8:08





                        I did the use the drop event, it doesn't fire anything when I drop.

                        – Sumchans
                        Dec 26 '17 at 8:08











                        0














                        This is this the way I got it working.
                        preventDefault() functions throws error, changed it for return false which worked fine. Thanks guys for the prompt responses.



                         drag(channel) {
                        console.log(channel);
                        }
                        onDragOver(channel: any) {
                        console.log("Drag Over");
                        return false;
                        }
                        onDrop(e:any) {
                        console.log("Drop");
                        }





                        share|improve this answer




























                          0














                          This is this the way I got it working.
                          preventDefault() functions throws error, changed it for return false which worked fine. Thanks guys for the prompt responses.



                           drag(channel) {
                          console.log(channel);
                          }
                          onDragOver(channel: any) {
                          console.log("Drag Over");
                          return false;
                          }
                          onDrop(e:any) {
                          console.log("Drop");
                          }





                          share|improve this answer


























                            0












                            0








                            0







                            This is this the way I got it working.
                            preventDefault() functions throws error, changed it for return false which worked fine. Thanks guys for the prompt responses.



                             drag(channel) {
                            console.log(channel);
                            }
                            onDragOver(channel: any) {
                            console.log("Drag Over");
                            return false;
                            }
                            onDrop(e:any) {
                            console.log("Drop");
                            }





                            share|improve this answer













                            This is this the way I got it working.
                            preventDefault() functions throws error, changed it for return false which worked fine. Thanks guys for the prompt responses.



                             drag(channel) {
                            console.log(channel);
                            }
                            onDragOver(channel: any) {
                            console.log("Drag Over");
                            return false;
                            }
                            onDrop(e:any) {
                            console.log("Drop");
                            }






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Dec 26 '17 at 19:38









                            SumchansSumchans

                            1981518




                            1981518






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f47975237%2fhtml-5-drag-drop-with-angular-4%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Ottavio Pratesi

                                Tricia Helfer

                                15 giugno