【问题标题】:Why does clearing date input using Angular give different results?为什么使用 Angular 清除日期输入会给出不同的结果?
【发布时间】:2020-02-10 04:12:05
【问题描述】:

我的 Angular 项目中有一个组件,它显示了用户选择的特定日期的图表。日期输入中的值必须是有效日期。所以当点击日期选择器上的 x 按钮时,它应该转到当前日期而不是空白。

这是html:

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

以及组件TS文件中的如下代码:

endDate = new Date();

setEndDate(newValue) {

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

  this.endDate = new Date();
}

我无法理解的是,有时它有效,有时却无效。 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.它应该保持在当前日期。

从测试来看,似乎正在设置值,但由于某种原因选择器没有更新。我试过改变绑定,但这只会导致它完全破坏。任何可以解释为什么这有时有效但有时无效的任何信息将不胜感激。

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

【问题讨论】:

  • 你能提供一个stackblitz或类似的东西吗?
  • @Yvan 现已添加到问题中

标签: html angular date data-binding


【解决方案1】:

我使用 viewChild 来设置 nativeElement 的值。看起来 endDate 在清除值后从未通过输入日期。我在 ts 文件中使用了 datePipe 来格式化日期。不要忘记将日期管道添加到模块中的提供程序中。

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

让我知道它是否适合您。

【讨论】:

  • 这似乎按预期工作。您能否详细说明为什么我的解决方案不起作用?这是我问题的重点
  • 我在测试过程中看到的是输入数据在单击“x”后忽略了 ngModel 设置的值,我不知道发生了什么,我用谷歌搜索并没有找到关于你的问题的任何事情。对此感到抱歉。
  • 但是如果你找到任何解释我很感兴趣
猜你喜欢
  • 2012-06-09
  • 2014-02-01
  • 2021-08-26
  • 2022-10-13
  • 1970-01-01
  • 2021-11-26
  • 2015-11-16
  • 2019-10-02
  • 2010-10-29
相关资源
最近更新 更多