From 9cff8c73b55fd90744314e16d34ecc9b780f08a1 Mon Sep 17 00:00:00 2001 From: mmalerba Date: Mon, 31 Jul 2017 11:23:36 -0700 Subject: [PATCH] fix(datepicker): fix error when selecting month with fewer days in year (#6129) view --- src/lib/datepicker/year-view.spec.ts | 16 ++++++++++++++-- src/lib/datepicker/year-view.ts | 4 +++- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/src/lib/datepicker/year-view.spec.ts b/src/lib/datepicker/year-view.spec.ts index 6d3714d2044..f44ec3ac9f9 100644 --- a/src/lib/datepicker/year-view.spec.ts +++ b/src/lib/datepicker/year-view.spec.ts @@ -1,10 +1,10 @@ import {async, ComponentFixture, TestBed} from '@angular/core/testing'; -import {Component} from '@angular/core'; +import {Component, ViewChild} from '@angular/core'; import {By} from '@angular/platform-browser'; import {MdYearView} from './year-view'; import {MdCalendarBody} from './calendar-body'; import {MdNativeDateModule} from '../core/datetime/index'; -import {FEB, JAN, MAR} from '../core/testing/month-constants'; +import {FEB, JAN, JUL, JUN, MAR} from '../core/testing/month-constants'; describe('MdYearView', () => { beforeEach(async(() => { @@ -76,6 +76,16 @@ describe('MdYearView', () => { expect((cellEls[0] as HTMLElement).innerText.trim()).toBe('JAN'); expect(cellEls[0].classList).toContain('mat-calendar-body-active'); }); + + it('should allow selection of month with less days than current active date', () => { + testComponent.date = new Date(2017, JUL, 31); + fixture.detectChanges(); + + expect(testComponent.yearView._monthSelected(JUN)); + fixture.detectChanges(); + + expect(testComponent.selected).toEqual(new Date(2017, JUN, 30)); + }); }); describe('year view with date filter', () => { @@ -108,6 +118,8 @@ describe('MdYearView', () => { class StandardYearView { date = new Date(2017, JAN, 5); selected = new Date(2017, MAR, 10); + + @ViewChild(MdYearView) yearView: MdYearView; } diff --git a/src/lib/datepicker/year-view.ts b/src/lib/datepicker/year-view.ts index a2fe2952990..91c34893ed5 100644 --- a/src/lib/datepicker/year-view.ts +++ b/src/lib/datepicker/year-view.ts @@ -95,9 +95,11 @@ export class MdYearView implements AfterContentInit { /** Handles when a new month is selected. */ _monthSelected(month: number) { + let daysInMonth = this._dateAdapter.getNumDaysInMonth( + this._dateAdapter.createDate(this._dateAdapter.getYear(this.activeDate), month, 1)); this.selectedChange.emit(this._dateAdapter.createDate( this._dateAdapter.getYear(this.activeDate), month, - this._dateAdapter.getDate(this.activeDate))); + Math.min(this._dateAdapter.getDate(this.activeDate), daysInMonth))); } /** Initializes this month view. */