mhfour
mhfour

Reputation: 265

How can I set min/max date to current date in HTML?

I have a date input in my project and I would like to set the min/max date to the current date. How can I achieve this in Angular 6?

I've tried to add let date = new Date(); to my ngOnInit and added the max in the HTML file to {{this.date}} but it does not disable the future dates.

HTML

<input type="date" formControlName="dob" class="form-control" id="dob" max="{{this.date}}">

TS

ngOnInit() {
  let date = new Date;
}

Upvotes: 6

Views: 34584

Answers (3)

ramses728
ramses728

Reputation: 343

The date variable that you are referencing has local scope in the ngOnInit() method. You have to declare the variable at the class scope so that it is available via the this pointer/keyword.

Concretely

import {
  Component,
  OnInit
} from '@angular/core';

@Component({
  selector: 'app-root',
  template: '<input type="date" max="{{this.date}}">',
})
export class AppComponent implements OnInit {
  date;

  ngOnInit() {
    this.date = new Date().toISOString().slice(0, 10);
  }
}

Cannot test at the moment please test in your scenario

Edit: was able to test, the above solution works in my testing

Upvotes: 3

JossFD
JossFD

Reputation: 2216

Keeping your way of doing it:

<input type="date"  class="form-control" id="dob" max="{{date | date:'yyyy-MM-dd'}}">

You need to pipe the date to follow the input format.

Upvotes: 20

Prashant Pimpale
Prashant Pimpale

Reputation: 10707

Try:

<input type="date" formControlName="dob" class="form-control" id="dob" [max]="date">

Upvotes: -1

Related Questions