You have unlimited access as a PRO member
You are receiving a free preview of 3 lessons
Your free preview as expired - please upgrade to PRO
Recent Posts
- Object Oriented Programming With TypeScript
- Angular Elements Advanced Techniques
- TypeScript - the Basics
- The Real State of JavaScript 2018
- Cloud Scheduler for Firebase Functions
- Testing Firestore Security Rules With the Emulator
- How to Use Git and Github
- Infinite Virtual Scroll With the Angular CDK
- Build a Group Chat With Firestore
- Async Await Pro Tips
Hold-to-Delete Angular Directive With RxJS and Firestore
Episode 139 written by Jeff DelaneyHealth Check: This lesson was last reviewed on and tested with these packages:
- Angular v6
- RxJS v6.2
Find an issue? Let's fix it
Source code for Hold-to-Delete Angular Directive With RxJS and Firestore on Github
Have you ever clicked a button by accident, only to have it that delete something valuable with on option to undo? It’s pretty annoying when this happens and there are many different UI elements we can use to prevent it. In the following lesson, you will learn how to use an Angular Attribute Directive to build a hold-to-delete button that requires the user to hold down on the mouse before triggering a delete operation.
Holdable Directive
The holdable
directive’s role is to listen to events on its host element, then calculate the time difference between mousedown and mouseup. It will emit a custom event to the parent component every 100ms, making it easy to animate a progress bar.
We use an RxJS Subject
to manage the state of the button, which has two possible state (1) the user is holding down or (2) they are not. The takeUntil
operator allows us to cancel an interval when the state changes to cancel.
import { Directive, HostListener, EventEmitter, Output } from '@angular/core'; |
Using the Directive for Firestore Deletion
Now that we have a way to track the “hold time” on an element, we can write an event handler that will listen to it and delete a record from the database after 1000ms. The first step is to attach the directive to a host element, such as a button. I’m also adding a progress bar to show the user how close they are to deletion.
|
Inside a component, you should have a delete event handler that will wait for the value to exceed a certain point, then trigger the backend operation.
@Component(...) |