-
Notifications
You must be signed in to change notification settings - Fork 9
/
interval.component.ts
71 lines (64 loc) · 2.04 KB
/
interval.component.ts
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
64
65
66
67
68
69
70
71
import {ChangeDetectionStrategy, Component, Injector, Input} from '@angular/core';
import {interval} from 'rxjs/observable/interval';
import {map} from 'rxjs/operators';
import {Subscription} from 'rxjs/Subscription';
import {Observable} from 'rxjs/Observable';
import {TreeNode} from '../../../common/tree-node.class';
import {Lifecycle} from '../../../common/utils/Lifecycle';
@Component({
selector: 'interval',
templateUrl: './interval.component.html',
styleUrls: ['./interval.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush
})
@Lifecycle({defaultName: true})
export class IntervalComponent extends TreeNode {
@Input() public runOutside: string;
@Input() public setInterval: string;
@Input() public asyncPipe: string;
public enabled: boolean;
public formatDate: string;
public timerSub: Subscription;
public timerObservable: Observable<string>;
public timer: number;
constructor(context: Injector) {
super(context);
this.formatDate = this.getFormattedDate();
}
public enableInterval() {
if (this.setInterval) {
this.timerInterval();
} else if (this.runOutside) {
this.zone.runOutsideAngular(() => {
const timer = interval(1000).pipe(map(this.getFormattedDate));
this.timerSub = timer.subscribe((time) => {
this.formatDate = time;
this.cd.detectChanges();
});
});
} else {
this.zone.runOutsideAngular(() => { // but async pipe execute main zone
this.timerObservable = interval(1000).pipe(map(this.getFormattedDate));
});
}
}
public updateInterval(enable: boolean) {
if (enable) {
this.enableInterval();
} else {
if (this.timerSub) {
this.timerSub.unsubscribe();
}
this.timerObservable = null;
clearInterval(this.timer);
}
}
private timerInterval() {
this.timer = window.setInterval(() => {
this.formatDate = this.getFormattedDate();
}, 1000);
}
private getFormattedDate() {
return new Date().toJSON().substring(10, 19).replace('T', '');
}
}