import {Component, ElementRef, HostListener, Renderer2, ViewChild} from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
@ViewChild('testArea') el: ElementRef;
newElement: any;
area = {
firstPoint : {
x: null,
y: null
},
lastPoint: {
x: null,
y: null
}
};
@HostListener('mouseup', ['$event'])
onMouseUp(event) {
this.area.lastPoint.x = event.clientX;
this.area.lastPoint.y = event.clientY;
setTimeout(() => this.createSelectArea('selected-area'), 500);
}
@HostListener('mousedown', ['$event'])
sendPosition(event) {
this.area.firstPoint.x = event.clientX;
this.area.firstPoint.y = event.clientY;
}
constructor(
private element: ElementRef,
private renderer: Renderer2
) {}
createElement(elClass: string) {
this.newElement = this.renderer.createElement('div');
this.renderer.addClass(this.newElement, elClass);
this.renderer.appendChild(this.el.nativeElement, this.newElement);
}
setSelectPosition(pointX, pointY, width, height) {
this.renderer.setStyle(this.newElement, 'left', (pointX - Math.abs(width)) + 'px');
this.renderer.setStyle(this.newElement, 'top', (pointY - Math.abs(height)) + 'px');
}
createSelectArea(elClass: string) {
const width = this.area.firstPoint.x - this.area.lastPoint.x;
const height = this.area.firstPoint.y - this.area.lastPoint.y;
this.createElement(elClass);
this.renderer.setStyle(this.newElement, 'width', Math.abs(width) + 'px');
this.renderer.setStyle(this.newElement, 'height', Math.abs(height) + 'px');
if ((width > 0) && (height > 0)) {
this.setSelectPosition(this.area.lastPoint.x, this.area.lastPoint.y, 0, 0);
} else if ((width < 0) && (height < 0)) {
this.setSelectPosition(this.area.firstPoint.x, this.area.firstPoint.y, 0, 0);
} else if ((width < 0) && (height > 0)) {
this.setSelectPosition(this.area.lastPoint.x, this.area.lastPoint.y, width, 0);
} else if ((height < 0) && (width > 0)) {
this.setSelectPosition(this.area.lastPoint.x, this.area.lastPoint.y, 0, height);
}
}
deleteLastFrame() {
this.renderer.removeChild(this.el, this.newElement);
}
}