Creating a Draggable modal using a Directive

Mohammedfahimullah
2 min readJun 18, 2021

In this article, we will see how we are going to implement a draggable modal using a directive.

First, we need to create a directive using the below command

ng g d draggable

We will be using HostListener, AfterViewInit, ElementRef.Make sure you import them in your draggable directive. In the ngAfterViewInit cycle, we will be accessing the element, changing the cursor of the element. In the HostListener we will be using mousedown mouseup , mousemove, mouseleave events.

MouseDown : The mousedown event occurs when the left mouse button is pressed down over the selected element.

MouseUp : The mouseup event occurs when the left mouse button is released over the selected element.

MouseMove : The mousemove event occurs whenever the mouse pointer moves within the selected element

MouseLeave: The mouseleave event occurs when the mouse pointer leaves the selected element.

this.modalElement = element.closest(".modal-content");

.closest will return the element that matches .modal-content.

if (event.button === 2 || !this.handleElement) {
return;

event. button = 1 represents the left click. event .button = 2 represents the right click of the mouse. Since we need to avoid the dragging of popup using the right click we have added the above condition.this.handleElement variable stores the element where the directive has been added.We need to return if the handleElement is null.

if (event.target !== this.handleElement &&!this.searchParentNode(<any>event.target, this.handleElement)) { return;

Dragging shouldn’t be allowed if the target and the handleElement does not match.This part of code handles that and the second part this.searchParentNode() methods allow you to drag the element even on pressing the child elements. Eg. By holding on to the modal-title(Add Modal) you can drag the modal which you can see in HTML file.

Now coming to the HTML part, we need to add the directive selector(appDraggable) to the element where the movable control has to be provided. From the below code we can see we have added the control to the modal header.

app.component.html

<div class="modal-header" appDraggable>
<h5 class="modal-title">Add Modal</h5>
<button type="button" class="close pull-right outline-none" aria-label="Close"
(click)="modal.hide()">
<span aria-hidden="true">&times;</span>
</button>
</div>

I feel like this is the easiest way of implementing a draggable popup. I hope you guys like this article. Any comments are appreciated.

--

--