Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 58 additions & 3 deletions apps/rxjs/49-hold-to-save-button/src/app/app.component.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,24 @@
import { ChangeDetectionStrategy, Component } from '@angular/core';
import {
AfterViewInit,
ChangeDetectionStrategy,
Component,
DestroyRef,
ElementRef,
inject,
signal,
viewChild,
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import {
filter,
fromEvent,
interval,
merge,
switchMap,
takeUntil,
takeWhile,
tap,
} from 'rxjs';

@Component({
imports: [],
Expand All @@ -8,17 +28,52 @@ import { ChangeDetectionStrategy, Component } from '@angular/core';
<div
class="flex w-full max-w-screen-sm flex-col items-center gap-y-8 p-4">
<button
#sendBtn
class="rounded bg-indigo-600 px-4 py-2 font-bold text-white transition-colors ease-in-out hover:bg-indigo-700">
Hold me
</button>

<progress [value]="20" [max]="100"></progress>
<progress [value]="progressBarValue()" [max]="100"></progress>
</div>
</main>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AppComponent {
export class AppComponent implements AfterViewInit {
sendBtn = viewChild<ElementRef<HTMLButtonElement>>('sendBtn');
progressBarValue = signal(0);
destroyRef = inject(DestroyRef);

ngAfterViewInit(): void {
const sendBtn = this.sendBtn();
if (!sendBtn) {
return;
}

const mouseDown$ = fromEvent(sendBtn.nativeElement, 'mousedown');
const mouseUp$ = fromEvent(sendBtn.nativeElement, 'mouseup');
const mouseLeave$ = fromEvent(sendBtn.nativeElement, 'mouseleave');

mouseDown$
.pipe(
switchMap(() =>
interval(10).pipe(
takeUntilDestroyed(this.destroyRef),
takeUntil(merge(mouseUp$, mouseLeave$)),
takeWhile(() => this.progressBarValue() < 100),
tap(() => this.progressBarValue.update((val) => val + 1)),
filter(() => this.progressBarValue() === 100),
tap(() => this.onSend()),
),
),
)
.subscribe();

merge(mouseUp$, mouseLeave$)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(() => this.progressBarValue.set(0));
}

onSend() {
console.log('Save it!');
}
Expand Down
Loading