Repository navigation
Expand file tree
/
Copy pathcounter.component.ts
More file actions
63 lines (58 loc) · 1.96 KB
/
Copy pathcounter.component.ts
File metadata and controls
63 lines (58 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import {
ChangeDetectionStrategy,
Component,
computed,
effect,
signal,
untracked,
} from '@angular/core';
const DEFAULT_COUNTER = {
count: 0,
ticking: false,
speed: 1000,
up: true,
diff: 1,
adhocCount: 10,
};
@Component({
selector: 'app-counter',
templateUrl: './counter.component.html',
styleUrls: ['./counter.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CounterComponent {
counter = signal(DEFAULT_COUNTER);
ticking = computed(() => this.counter().ticking);
speed = computed(() => this.counter().speed);
diff = computed(() => this.counter().diff);
up = computed(() => this.counter().up);
adhocCount = computed(() => this.counter().adhocCount);
start = () => this.counter.update((v) => ({ ...v, ticking: true }));
stop = () => this.counter.update((v) => ({ ...v, ticking: false }));
countUp = () => this.counter.update((v) => ({ ...v, up: true }));
countDown = () => this.counter.update((v) => ({ ...v, up: false }));
incrementBy = (diff: number) => this.counter.update((v) => ({ ...v, diff }));
setSpeed = (speed: number) => this.counter.update((v) => ({ ...v, speed }));
setCount = (count: number) => this.counter.update((v) => ({ ...v, count, adhocCount: count }));
setAdhocCount = (adhocCount: number) => this.counter.update((v) => ({ ...v, adhocCount }));
reset = () => this.counter.set(DEFAULT_COUNTER);
ticker = effect(() => {
const ticking = this.ticking();
const speed = this.speed();
const diff = this.diff();
const up = this.up();
untracked(() => this.tick(ticking, speed, diff, up));
});
interval: NodeJS.Timeout | undefined = undefined;
tick(ticking: boolean, speed: number, diff: number, up: boolean) {
clearInterval(this.interval);
if (ticking) {
const increment = up ? diff : diff * -1;
this.interval = setInterval(
() =>
this.counter.update((v) => ({ ...v, count: v.count + increment })),
speed
);
}
}
}