【问题标题】:How to set input type date value of max="variable value"如何设置 max="variable value" 的输入类型日期值
【发布时间】:2019-01-27 07:12:32
【问题描述】:

无法获取“输入字段的“最大”属性的今天日期值”,但可以在控制台中获取该值。

你们能帮我如何在输入字段中获取价值(即 max="2018-08-21")

var todayDate =
      new Date().getFullYear() +
      "-" +
      ("0" + (new Date().getMonth() + 1)).slice(-2) +
      "-" +
      ("0" + new Date().getDate()).slice(-2);
    console.log(todayDate, "here");
 <div class="input-group">
    <input type="date" max="todayDate" />
 </div>

【问题讨论】:

  • 你的Javascript应该在HTML之前
  • 处理日期时应使用momentjs

标签: html angular typescript


【解决方案1】:

当您使用 Angular 时,您可以将 max 与日期绑定为:

TS

todayDate = new Date().getFullYear() + "-" + ("0" + (new Date().getMonth() + 1)).slice(-2) + "-" + ("0" + new Date().getDate()).slice(-2);

HTML

<div class="input-group">
  <input type="date" [max]="todayDate" />
</div>

你可以查看stackblitz here

【讨论】:

  • @MalathyVenkatesan 太好了,您可以投票并接受答案:)
【解决方案2】:

使用[max]

export class AppComponent  {

  todayDate = new Date('2018-08-21')

}

<div class="input-group">
  <input type="date" [max]="todayDate | date:'yyyy-MM-dd'" />
</div>

【讨论】:

    【解决方案3】:

    由于没有人为您提供 Angular 答案,而是依靠您的语言环境来测试它(这样做很危险),所以它是:一个自定义验证器,它将检查日期是否低于您提供的日期给验证者。 Here is a stackblitz demo

    验证器:

    export function notAfterToday(date: Date = new Date(Date.now())): ValidatorFn {
      return (control: AbstractControl): { [key: string]: any } | null => {
        const selectedDate = new Date(control.value);
        return selectedDate && !isNaN(selectedDate.getTime()) && selectedDate.getTime() > date.getTime() ? { 'dateTooHigh': true } : null;
      };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-25
      • 2022-12-05
      • 2016-05-27
      • 2014-09-24
      • 2015-12-15
      • 2020-01-02
      • 2019-10-04
      • 1970-01-01
      相关资源
      最近更新 更多