Sasika Miyuran
Sasika Miyuran

Reputation: 185

How to get Previous date Angular date picker

I'm using Angular Material DatePicker like this

<input matInput [(ngModel)]="selectedDate" [max]="today" (dateChange)="onDateSelect($event)"
              [matDatepicker]="picker" readonly />

And I need to set the last selected date in

onDateSelect()

function. the function is like follows

 onDateSelect(event) {
    if(some condition){
      this.selectedDate = <//set previous date>
    }
    this.selectedDate = event.value;   
 }

how can I pass the previous date to the above function

Upvotes: 0

Views: 1893

Answers (3)

Eliseo
Eliseo

Reputation: 57939

another option is use a FormControl, and pairwise

selectedDate=new FormControl()
ngOnInit()
{
   this.selectedDate.valueChanges.pipe(
      startWith(this.selectedDate.value), //it's necesary send a first value
      pairwise())  //the pairwise make the "magic"
 .subscribe(([old,value])=>{
    if (old!=value)
    {
       console.log("I change from "+old+" to "+value)
    }
 })

<input matInput [formControl]="selectedDate" [max]="today" 
           [matDatepicker]="picker" readonly />

see the stackblitz

Upvotes: 1

huan feng
huan feng

Reputation: 8623

You need 2 variables for it, something like below:

Reset to previous if your validation is not passed.

JS:

export class DatepickerApiExample implements OnInit {
  previousVal: any;
  curVal: any;
  checkPassed: true;

  ngOnInit() {
    this.previousVal = this.curVal;
  }

  onDateSelect($event: any) {
    if (this.checkPassed) {
      this.previousVal = this.curVal;
    } else {
      //Reset to previous
      this.curVal = this.previousVal;
    }
  }
}

HTML:

<mat-form-field class="example-full-width" appearance="fill">
  <mat-label>Choose a date</mat-label>
  <input matInput [(ngModel)]="curVal" [max]="today" (dateChange)="onDateSelect($event)" [matDatepicker]="picker">
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

Upvotes: 0

Gopi krishna
Gopi krishna

Reputation: 355

Create a variable prevSelectedDate as null and add please add the below changes in code.

onDateSelect(event) {

if(some condition && this.prevSelectedDate){
  this.selectedDate = this.prevSelectedDate;
}
this.selectedDate = event.value;  
this.prevSelectedDate =  this.selectedDate

}

Upvotes: 0

Related Questions