【问题标题】:Object is possibly 'null' in Angular Form validationAngular 表单验证中的对象可能为“null”
【发布时间】:2021-05-22 22:11:56
【问题描述】:

我正在对表单进行验证,以检查输入的数字是否大于某个数字。 我试过这个answer,但我仍然遇到同样的错误。

但我收到以下错误:

error TS2531: Object is possibly 'null'.
 <small style="color: red;" [hidden]="myForm.get('checkAmount').hasError?'maxlength'">
                                                                ~~~~~~~~

  src/app/withdraw/withdraw.component.ts:10:16
    10   templateUrl: './withdraw.component.html',
                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component WithdrawComponent.

这是我的代码:

<form [formGroup]="myForm" class="space" method="POST" autocomplete="off">
    <input type="text" name="amount" size="230" placeholder="Amount To Withdraw" 
    formControlName="checkAmount"
    [(ngModel)]="model.Balance"
    maxlength=50
    >
    <small style="color: red;" [hidden]="myForm.get('checkAmount').hasError?'maxlength'">
        The value should not exceed the balance
    </small>
</form>

【问题讨论】:

  • myForm?.get('checkAmount')?.hasError?.'maxlength'"

标签: angular


【解决方案1】:

为了安全起见,您可以将? 运算符放在每个链接中:

[hidden]="myForm?.get('checkAmount')?.hasError('maxlength')"

【讨论】:

  • 编译成功了,但是还没填表就显示数据了。
  • 在填写表格之前,您没有遇到 maxlength 错误,对吧?因此,计算结果为 falsehidden="false" 确实会显示错误。您可以/应该恢复条件或使用*ngIf 而不是[hidden]
  • 在填写表格之前,已经显示“金额不应超过余额”。我会试试*ngIf
  • 如何恢复条件?
  • !(myForm?.get('checkAmount')?.hasError('maxlength'))
【解决方案2】:

试试这个

[hidden]="myForm.get('checkAmount').errors?.maxlength"

【讨论】:

    猜你喜欢
    • 2021-08-21
    • 2020-06-03
    • 2021-04-14
    • 2021-09-16
    • 2017-09-29
    • 1970-01-01
    • 2016-04-01
    • 2021-08-08
    • 2014-11-06
    相关资源
    最近更新 更多