Managing a project that involves a container holding multiple cards across different pages can be overwhelming. To address this, the screen automatically rotates to the next page after a set time interval or when the user presses the space bar.
To enhance the functionality, we have introduced a toggle button to disable the automatic rotation. I have integrated an 'EventEmitter' for the toggle button in the 'toggleEmitter' function below, but as I am fairly new to rxjs, I am unsure how to utilize it effectively to halt the rotation process. Can anyone offer guidance on this matter?
@Component({
selector: 'rotator-container',
templateUrl: './rotator-container.component.html',
})
export class RotatorContainerComponent implements AfterViewInit, OnDestroy {
@ContentChildren(RotatorItemComponent, { read: ElementRef })
rotatorItems: QueryList<ElementRef>;
@Input() rotationInterval = 30 * 1000;
@Output() toggleEmitter: EventEmitter<MatSlideToggleChange> =
new EventEmitter();
toggle(event: MatSlideToggleChange) {
this.toggleEmitter.emit(event);
}
timer$ = this.activatedRoute.queryParams.pipe(
map(params => params['rotate']),
switchMap(rotate =>
rotate === 'false' ? of(0) : timer(0, this.rotationInterval)
)
);
spaceCounter$ = fromEvent<KeyboardEvent>(document, 'keydown').pipe(
filter(({ code }) => code === 'Space'),
tap(e => e.preventDefault()),
map(() => 1),
scan((acc, curr) => acc + curr, 0),
startWith(0)
);
rotationCounter$ = combineLatest([this.timer$, this.spaceCounter$]).pipe(
map(([index, offset]) => index + offset)
);
rotatorSubscription: Subscription;
constructor(private activatedRoute: ActivatedRoute) {}
ngAfterViewInit() {
const rotatorItemsLength$ = this.rotatorItems.changes.pipe(
map(() => this.rotatorItems.length),
startWith(this.rotatorItems.length)
);
const visibleIndex$ = combineLatest([
this.rotationCounter$,
rotatorItemsLength$,
]).pipe(
map(([index, length]) => index % length),
startWith(0)
);
this.rotatorSubscription = visibleIndex$.subscribe(visibleIndex =>
this.rotatorItems.forEach((item, index) => {
(<HTMLElement>item.nativeElement).style.visibility =
visibleIndex === index ? 'visible' : 'hidden';
(<HTMLElement>item.nativeElement).style.position =
visibleIndex === index ? 'relative' : 'absolute';
})
);
}
ngOnDestroy() {
this.rotatorSubscription && this.rotatorSubscription.unsubscribe();
}
}