html - 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
解决方案
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.
推荐阅读
- python - Python中的类变量和实例变量
- javascript - 列中的 JS 条件模板
- php - wp-admin/admin-AJAX 403 禁止
- ios - 如何在 WKWebview 中添加观察者以播放和暂停音频文件的操作?
- flutter - 在 CupertinoTabBar 视图内外导航
- google-cloud-platform - 聚合时是否可以使堆栈驱动程序监视不填充时间序列间隙
- typescript - 为什么 Typescript 将 `object.hasOwnProperty("key")` 视为与 `"key" in object` 本质上不同
- sql - SQL - XML - 在子查询中创建多个具有相同名称的节点
- c++ - Wincrypto (CNG):无法使用任何 CNG 算法创建证书
- maps - 将像素转换为 Mapbox 地图上的坐标