ts檔不變,把縮放的功能抓出來放在directive,方便未來的應用
這裡用三種形狀展示,分別是矩形、圓形、圓角矩形
今天的內容一樣也放在 StackBlitz
首先建立ResizableDirective,在AppModule宣告
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { DragDropModule } from '@angular/cdk/drag-drop'
import { AppComponent } from './app.component';
import { ResizableDirective } from './resizable.directive';
import { RotatableDirective } from './rotatable.directive';
@NgModule({
declarations: [
AppComponent,
ResizableDirective,
],
imports: [
BrowserModule,
DragDropModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';
@Directive({
selector: '[resizable]'
})
export class ResizableDirective {
constructor(private el: ElementRef, private renderer: Renderer2) {}
@HostListener('mousedown', ['$event'])
onMouseDown(event: MouseEvent) {
event.preventDefault();
const initialWidth = this.el.nativeElement.offsetWidth;
const initialHeight = this.el.nativeElement.offsetHeight;
const startX = event.clientX;
const startY = event.clientY;
const onMouseMove = (moveEvent: MouseEvent) => {
const newWidth = initialWidth + (moveEvent.clientX - startX);
const newHeight = initialHeight + (moveEvent.clientY - startY);
this.renderer.setStyle(this.el.nativeElement, 'width', `${newWidth}px`);
this.renderer.setStyle(this.el.nativeElement, 'height', `${newHeight}px`);
};
const onMouseUp = () => {
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
};
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
}
}
.shape-container {
display: flex;
gap: 20px;
}
.shape {
border: 1px solid #000;
background-color: #f0f0f0;
}
.rectangle {
width: 100px;
height: 50px;
}
.circle {
width: 100px;
height: 100px;
border-radius: 50%;
}
.ellipse {
width: 150px;
height: 100px;
border-radius: 10px;
}