import { Injectable , OnDestroy } from '@angular/core' ; import { BehaviorSubject , Subscription } from 'rxjs' ; import { DatePickerHeaderEvent , DateTimePickerService , YearRange } from '../date-time-picker.service' ; import { gridify , range } from '../date-time-picker.utils' ; @ Injectable ( ) export class YearViewService implements OnDestroy { grid$ = new BehaviorSubject < YearViewItem [ ] [ ] > ( [ [ ] ] ) ; focused$ = new BehaviorSubject < number > ( null ) ; private _year : number = new Date ( ) . getFullYear ( ) ; private _subscription = new Subscription ( ) ; constructor ( private _datepicker ) { const year = _datepicker . year$ . subscribe ( _year => this . createYearGrid ( _year ) ) ; const event = _datepicker . headerEvent$ . subscribe ( _event => _event === DatePickerHeaderEvent . Next ? this . goToNextDecade ( ) : this . goToPreviousDecade ( ) ) ; this . _subscription . add ( year ) ; this . _subscription . add ( event ) ; } ngOnDestroy ( ) { this . _subscription . unsubscribe ( ) ; } setFocus ( year ) { this . focused$ . next ( year ) ; this . createYearGrid ( year ) ; } goToPreviousDecade ( ) { this . createYearGrid ( this . _year - 10 ) ; } goToNextDecade ( ) { this . createYearGrid ( this . _year + 10 ) ; } private createYearGrid ( year = this . _year ) { this . _year = year ; const decade = this . getDecade ( year ) ; const currentYear = new Date ( ) . getFullYear ( ) ; const items = decade . range . map ( _year => { return { year : _year , isCurrentYear : _year === currentYear , isActiveYear : _year === this . _datepicker . year$ . value } ; } ) ; this . _datepicker . setHeader ( decade . start + ' - ' + decade . end ) ; this . grid$ . next ( gridify ( items , 4 ) ) ; } /**
     * Get the years in the current decade to display
     */ private getDecade ( year ) { const start = ( year - ( year % 10 ) ) ; const end = start + 9 ; this . _datepicker . yearRange = { start , end , range : range ( start , end ) } ; return this . _datepicker . yearRange ; } } export interface YearViewItem { year : number ; isCurrentYear : boolean ; isActiveYear : boolean ; }