1

I have an input of type date, and I need that it is not possible to select a date that is not from today, I tried it this way, but I was not very successful:

HTML:

<input [(ngModel)]="atv.dataini" type="date" class="form-control" #one min="{{this.today}}">

TYPESCRIPT:

today = this.dNow.getFullYear() + '-0' + (this.dNow.getMonth() + 1) + '-0' + this.dNow.getDate();

I also tried it this way:

HTML:

<input [(ngModel)]="atv.dataini" type="date" class="form-control" #one min="{{this.tdNow}}">

TYPESCRIPT:

dNow = this.formatDate(new Date());

formatDate(date) {
    let result = date.split('-').reverse().join('/');
    return result
}
Nicholas K
  • 15,148
  • 7
  • 31
  • 57

2 Answers2

2

So, I mean you have some ways to do that, but I guess the most correct one is to let the user input a data, and compare with the daynow, and show a message.

To get the daynow on JS:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now

I think that's can help too:

Compare two dates with JavaScript

Eduardo Fellipe
  • 376
  • 2
  • 14
0

The complete solution would be along the lines of:

.html

<input #dateInput type="date" [(ngModel)]="myDate"> 

.ts

@ViewChild("dateInput", { static: false }) input: ElementRef;
myDate: string;

ngAfterViewInit(): void {
  const keyUpObservable = fromEvent(this.input.nativeElement, "change");
  keyUpObservable
    .pipe(
      map((event: any) => event.target.value),
      debounceTime(2000),
      distinctUntilChanged()
    )
    .subscribe((date: string) => {
      const today = new Date();
      if (new Date(date.toString()) < today) {
        this.myDate = today.toISOString().split("T")[0];
      } else {
        this.myDate = date;
      }
    });
}
  • Here, a reference of the input box is obtained and an observable is created on the change event (either by pressing a key or by click).
  • Next, debounceTime is used to emit this value when the user has stopped typing after 2s. (You can edit the delay based on your preferences)
  • The distinctUntilChanged prevents the observable from being emitted if there is no change between the current and previous input values.

Working stackblitz.

Nicholas K
  • 15,148
  • 7
  • 31
  • 57