5

我正在研究mat-datepicker用户可以在哪里输入值并使用我的代码选择日期它工作正常。默认情况下,我有一个更新按钮,它将处于禁用模式。当用户满足两个条件时,只有更新按钮才会启用。

这是我的屏幕截图,它看起来像

在此处输入图像描述

如果我清除最后一个日期,一旦用户输入最后一个日期,更新按钮将处于禁用模式,那么只有更新将在此处启用我遇到了问题

这是我的 ts 代码

dateValidator(input) {
    //console.log(input);
    console.log(Object.prototype.toString.call(input) === '[object Date]', !this.disableDate(), input.length > 0)
    if (!!input) { // null check
        if (Object.prototype.toString.call(input) === '[object Date]' && !this.disableDate() && input.length > 0) {
            this.disableUpdateBtn = false;
            console.log("Date is Valid!!");
        } else {
        this.disableUpdateBtn = true;
        console.log("Date is Invalid!!");
        }
    } else {
        this.disableUpdateBtn = true;
        console.log("Date is Invalid!!");
    }
}

这是我HTML的更新按钮代码

<button mat-flat-button color="primary" (click)="updateMilestone();" cdkFocusInitial [disabled]="disableUpdateBtn">
    Update
</button>

单击清除按钮时出现错误,然后开始输入日期,然后输入01. 我没有收到任何错误,但是当我开始输入Dec.

在此处输入图像描述

我正在检查 if 条件中的输入是否为 null 为什么仍然无法读取 null 属性

4

2 回答 2

2

尝试将其更改input.length为:input?.length在您的代码中(所有实例)

于 2021-12-11T09:10:14.243 回答
1

控制台上出现的错误就console.log行了(在null检查之前):

dateValidator(input) {
    // error on the next line, because `input` is `null`, and you're trying to read the `length`.
    console.log(Object.prototype.toString.call(input) === '[object Date]', !this.disableDate(), input.length > 0)
    if (!!input) { // null check
        ...
    }
    ...
}

为了解决这个问题,要么:

  1. 通过更改 to 的所有实例来使用可选链接input.lengthinput?.length
dateValidator(input) {
    console.log(Object.prototype.toString.call(input) === '[object Date]', !this.disableDate(), input?.length > 0)
    if (!!input) { // null check
        ...
    }
    ...
}
  1. 或者,在空检查范围console.log内移动该行。if
dateValidator(input) {
    if (!!input) { // null check
        console.log(Object.prototype.toString.call(input) === '[object Date]', !this.disableDate(), input.length > 0)
    }
    ...
}
  1. 或者,只需删除该console.log行。
于 2021-12-12T13:41:23.810 回答