People who are familiar with Figma would have noticed that the input fields support dragging to increase or decrease values. Instead of having to click on the input field first and then type the number in, the dragging feature is really handy as you can easily get the desired value by dragging.
We can build something like that using Angular directives. We’ll use all the latest features of Angular in this experiment.
Let's see how we can build this.
We can actually do this in multiple ways. We are going to build this using directives. The way we are going to do this is by taking a very generic approach. This way, we can reuse the logic for things like resizing elements or sidebars, etc.
Scrubber Directive - the core functionality
The main logic of the input can be extracted and encapsulated into a directive. The main objective is to listen to the mouse events and then translate the mouse movements into a usable value. To explain in a bit more detail:
When the user clicks the mouse (mousedown event).
We start listening to the mouse movements (mousemove events) and use that info to translate it into usable values.
When the user releases the click, we stop the listener (mouseup event).
We will use rxjs to simplify the logic a bit.
Here's how the pseudocode would look.
const mousedown$ = fromEvent<mouseevent>(target, 'mousedown'); const mousemove$ = fromEvent<mouseevent>(document, 'mousemove'); const mouseup$ = fromEvent<mouseevent>(document, 'mouseup'); let startX = 0; let step = 1; mousedown$ .pipe( tap((event) => { startX = event.clientX; // Initial x co-ordinate where the mouse down happened }), switchMap(() => mousemove$.pipe(takeUntil(mouseup$)))) .subscribe((moveEvent) => { const delta = startX - moveEvent.clientX; const newValue = Math.round(startValueAtTheTimeOfDrag + delta); }); </mouseevent></mouseevent></mouseevent>
Looking at the above code, it should be pretty clear what is happening. We basically save the initial clientX value, which is the position of the click on the X axis. Once we have that info, when the user moves the mouse, we can calculate the delta from the initial start position and the current X position.
We can further add more customizations like:
Sensitivity - drag distance to final value will be decided by sensitivity. Higher sensitivity values mean the final value will be big even if the movement is not that much.
Step - sets the stepping interval when moving the mouse. If the step value is 1, the final value is incremented/decremented in steps of 1.
Min - minimum value that will be emitted.
Max - maximum value that will be emitted.
Here’s how the final directive would look:
@Directive({ selector: "[scrubber]", }) export class ScrubberDirective { public readonly scrubberTarget = input.required<htmldivelement>({ alias: "scrubber", }); public readonly step = model<number>(1); public readonly min = model<number>(0); public readonly max = model<number>(100); public readonly startValue = model(0); public readonly sensitivity = model(0.1); public readonly scrubbing = output<number>(); private isDragging = signal(false); private startX = signal(0); private readonly startValueAtTheTimeOfDrag = signal(0); private readonly destroyRef = inject(DestroyRef); private subs?: Subscription; constructor() { effect(() => { this.subs?.unsubscribe(); this.subs = this.setupMouseEventListener(this.scrubberTarget()); }); this.destroyRef.onDestroy(() => { document.body.classList.remove('resizing'); this.subs?.unsubscribe(); }); } private setupMouseEventListener(target: HTMLDivElement): Subscription { const mousedown$ = fromEvent<mouseevent>(target, "mousedown"); const mousemove$ = fromEvent<mouseevent>(document, "mousemove"); const mouseup$ = fromEvent<mouseevent>(document, "mouseup"); return mousedown$ .pipe( tap((event) => { this.isDragging.set(true); this.startX.set(event.clientX); this.startValueAtTheTimeOfDrag.set(this.startValue()); document.body.classList.add("resizing"); }), switchMap(() => mousemove$.pipe( takeUntil( mouseup$.pipe( tap(() => { this.isDragging.set(false); document.body.classList.remove("resizing"); }) ) ) ) ) ) .subscribe((moveEvent) => { const delta = moveEvent.clientX - this.startX(); const deltaWithSensitivityCompensation = delta * this.sensitivity(); const newValue = Math.round( (this.startValueAtTheTimeOfDrag() + deltaWithSensitivityCompensation) / this.step() ) * this.step(); this.emitChange(newValue); this.startValue.set(newValue); }); } private emitChange(newValue: number): void { const clampedValue = Math.min(Math.max(newValue, this.min()), this.max()); this.scrubbing.emit(clampedValue); } } </mouseevent></mouseevent></mouseevent></number></number></number></number></htmldivelement>
How to use the scrubber directive
Now that we have the directive ready, let’s see how we can actually start using it.
const mousedown$ = fromEvent<mouseevent>(target, 'mousedown'); const mousemove$ = fromEvent<mouseevent>(document, 'mousemove'); const mouseup$ = fromEvent<mouseevent>(document, 'mouseup'); let startX = 0; let step = 1; mousedown$ .pipe( tap((event) => { startX = event.clientX; // Initial x co-ordinate where the mouse down happened }), switchMap(() => mousemove$.pipe(takeUntil(mouseup$)))) .subscribe((moveEvent) => { const delta = startX - moveEvent.clientX; const newValue = Math.round(startValueAtTheTimeOfDrag + delta); }); </mouseevent></mouseevent></mouseevent>
Currently, we have marked the scrubberTarget input as input.required, but we can actually make it optional and automatically use the elementRef.nativeElement of the host of the directive, and it would work the same. The scrubberTarget is exposed as an input in case you want to set a different element as the target.
We also add a class resizing to the body so that we can set the resize cursor correctly.
@Directive({ selector: "[scrubber]", }) export class ScrubberDirective { public readonly scrubberTarget = input.required<htmldivelement>({ alias: "scrubber", }); public readonly step = model<number>(1); public readonly min = model<number>(0); public readonly max = model<number>(100); public readonly startValue = model(0); public readonly sensitivity = model(0.1); public readonly scrubbing = output<number>(); private isDragging = signal(false); private startX = signal(0); private readonly startValueAtTheTimeOfDrag = signal(0); private readonly destroyRef = inject(DestroyRef); private subs?: Subscription; constructor() { effect(() => { this.subs?.unsubscribe(); this.subs = this.setupMouseEventListener(this.scrubberTarget()); }); this.destroyRef.onDestroy(() => { document.body.classList.remove('resizing'); this.subs?.unsubscribe(); }); } private setupMouseEventListener(target: HTMLDivElement): Subscription { const mousedown$ = fromEvent<mouseevent>(target, "mousedown"); const mousemove$ = fromEvent<mouseevent>(document, "mousemove"); const mouseup$ = fromEvent<mouseevent>(document, "mouseup"); return mousedown$ .pipe( tap((event) => { this.isDragging.set(true); this.startX.set(event.clientX); this.startValueAtTheTimeOfDrag.set(this.startValue()); document.body.classList.add("resizing"); }), switchMap(() => mousemove$.pipe( takeUntil( mouseup$.pipe( tap(() => { this.isDragging.set(false); document.body.classList.remove("resizing"); }) ) ) ) ) ) .subscribe((moveEvent) => { const delta = moveEvent.clientX - this.startX(); const deltaWithSensitivityCompensation = delta * this.sensitivity(); const newValue = Math.round( (this.startValueAtTheTimeOfDrag() + deltaWithSensitivityCompensation) / this.step() ) * this.step(); this.emitChange(newValue); this.startValue.set(newValue); }); } private emitChange(newValue: number): void { const clampedValue = Math.min(Math.max(newValue, this.min()), this.max()); this.scrubbing.emit(clampedValue); } } </mouseevent></mouseevent></mouseevent></number></number></number></number></htmldivelement>
We have used effect to start the listener, this would make sure that when in case target element changes, we set the listener on the new element.
See it in action
We have made a super simple Scrubber directive in Angular which can help us build input fields similar to what Figma has. Makes is super easy for user to interact with numeric inputs.
Code & Demo
https://stackblitz.com/edit/figma-like-number-input-angular?file=src/scrubber.directive.ts
Connect with me
Twitter
Github
Linkedin
Do add your thoughts in the comments section. Stay Safe ❤️
The above is the detailed content of Figma like input field in Angular using Directives. For more information, please follow other related articles on the PHP Chinese website!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1
Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
