Alaksandar Jesus Gene
Alaksandar Jesus Gene

Reputation: 6887

Material Angular v10 Datepicker not working with min and max

I have a working datepicker working on v 9.x. The project was upgraded to v10 and now in the datepicker the dates are non-selectable

stackblitz link

If i remove the

[min]="min.startDate" [max]="min.endDate"

i was able to select dates.

I did cross verify with their api documentation and no change i could notify on their api.

https://material.angular.io/components/datepicker/api

Please let me know what am i missing out on the update.

Upvotes: 0

Views: 2034

Answers (3)

Jonathan Gonzalez
Jonathan Gonzalez

Reputation: 81

The solution is to convert the Moment to Dates, as follows:

public maxDate: Date = Moment(your max date).toDate();
public minDate: Date = Moment(your min date).toDate();

And the html might look like this:

<nb-datepicker
    #picker
    [max]="maxDate"
    [min]="minDate"
    [format]="dateFormat"
></nb-datepicker>

Upvotes: 2

Yuqiu G.
Yuqiu G.

Reputation: 345

I adjusted ts and html from the example to your files And it should be working now:

import { Component, VERSION } from "@angular/core";
import { FormBuilder } from "@angular/forms";
import moment from "moment";
import { Moment } from 'moment';
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  minDate: Moment;
  maxDate: Moment;

  constructor() {
    this.minDate = moment().subtract(1, 'year');
    this.maxDate = moment();
  }
}

<mat-form-field class="example-full-width" appearance="fill">
  <mat-label>Choose a date</mat-label>
  <input matInput [min]="minDate" [max]="maxDate" [matDatepicker]="picker">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

<div>
{{minDate}}

</div>
<div>
{{maxDate}}
</div>

Upvotes: 1

Dilshan
Dilshan

Reputation: 3001

I have tried it without moment and it is working.

You can do like this,

  minDate: Date;
  maxDate: Date;

  constructor() {
    const currentYear = new Date().getFullYear();
    this.minDate = new Date(currentYear - 1, 0, 1); // 2019 January 1st
    this.maxDate = new Date(currentYear + 1, 11, 31); // 2021 December 31st
  }

Example from the documentation - https://stackblitz.com/angular/jampmjpoympg?file=src%2Fapp%2Fdatepicker-min-max-example.ts

Upvotes: 1

Related Questions