首页 > 解决方案 > Why does clearing date input using Angular give different results?

问题描述

I have a Component in my Angular project that shows a graph up to a particular date as picked by the user. The value in the date input must be a valid date. So when clicking the x button on the date picker, it should go to the current date and not be blank.

This is the html:

<input class="form-control input-sm" type="date" name="endDate" 
        [ngModel]="endDate | date:'yyyy-MM-dd'" (ngModelChange)="setEndDate($event);">

and the following code in the Component TS file:

endDate = new Date();

setEndDate(newValue) {

  if(newValue) {
    this.endDate = newValue;
    return;
  }

  this.endDate = new Date();
}

What I can't get my head around is that sometimes it works and sometimes it doesn't. Specifically, when the date in the picker is not the current date, clicking the x results in it becoming the current date as intended. When the date in the picker is the current date, it goes blank and shows mm/dd/yyyy. It should just stay on the current date.

From testing it looks like the value is being set, but the picker does not update for some reason. I've tried changing the binding but this only resulted in it breaking completely. Any light that can be shed on why this works sometimes but not other times would be appreciated.

stackblitz: https://stackblitz.com/edit/angular-oep55t

标签: htmlangulardatedata-binding

解决方案


I use a viewChild for set the value of the nativeElement. Looks like endDate was never pass throught the input date after clear the value. I used the datePipe in the ts file in order to get the date formatted. Don't forget to add the datepipe into the providers in your module.

https://stackblitz.com/edit/angular-268qje

Let me know if it's ok for you.


推荐阅读