Each directive comes with its own functionality and specific features. It can be challenging to understand how to connect a variable from a directive to a component. This particular directive involves detecting x-axis and y-axis positions during mouse events, as well as utilizing a boolean variable called movable.
// Modules and Components
import { Directive, Input, ElementRef, HostBinding, HostListener } from '@angular/core';
import { DomSanitizer, SafeStyle } from '@angular/platform-browser';
// Directive
import { DraggableDirective } from '../draggable/draggable.directive';
// Interfaces
import { Position } from '../../../../interfaces/draggable-system/move-position';
/**
* Enables the movement of objects.
*/
@Directive({
selector: '[appMovable]'
})
export class MovableDirective extends DraggableDirective {
// ********** DECLARATIONS **********//
// Overview of the Inputs, Outputs, and HostBindings
@Input('appMovable') set movable(movable: boolean) {
this.enabled = movable;
}
@HostBinding('class.moving') moving = false;
// Check the positions
position: Position = { x: 0, y: 0 };
private startPosition: Position;
private reset = false;
constructor(
public element: ElementRef,
private sanitizer: DomSanitizer) {
super();
}
// Utilize HostBindings and HostListener
@HostBinding('style.transform') get transform(): SafeStyle {
return this.sanitizer.bypassSecurityTrustStyle(
`translateX(${this.position.x}px) translateY(${this.position.y}px)`
);
}
@HostListener('dragStart', ['$event']) onDragStart(event: PointerEvent): void {
this.moving = true;
this.startPosition = {
x: event.clientX - this.position.x,
y: event.clientY - this.position.y
};
}
@HostListener('dragMove', ['$event']) onDragMove(event: PointerEvent): void {
this.position = {
x: event.clientX - this.startPosition.x,
y: event.clientY - this.startPosition.y,
};
}
@HostListener('dragEnd') onDragEnd(): void {
this.moving = false;
if (this.reset) {
this.position = {
x: 0,
y: 0,
};
}
}
}