Ridwan Bhugaloo
Ridwan Bhugaloo

Reputation: 241

Object is possibly 'null' in Angular Form validation

I am doing a validation on a form to check if a number input is greater than a certain number. I tried this answer, but I am still getting the same error.

But in am getting the following error:

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.

Here is my code:

<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>

Upvotes: 1

Views: 3603

Answers (2)

eko
eko

Reputation: 40647

You can put the ? operator to every chaining to be safe:

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

Upvotes: 5

dev_101
dev_101

Reputation: 331

try this

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

Upvotes: 0

Related Questions