1

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>
1
  • myForm?.get('checkAmount')?.hasError?.'maxlength'" Commented May 23, 2021 at 14:18

2 Answers 2

5

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

[hidden]="myForm?.get('checkAmount')?.hasError('maxlength')"
Sign up to request clarification or add additional context in comments.

5 Comments

It has compiled successfully, but it is displaying the <small> data even before I fill in the form.
Well before you fill the form you don't have the maxlength error, right? Hence, that evaluates to false and hidden="false" would indeed display the error. You can/should revert the condition or use an *ngIf instead of [hidden]
Before filling the form, it is already displaying "The value should not exceed the balance". I will try the *ngIf
How do I revert the condition?
!(myForm?.get('checkAmount')?.hasError('maxlength'))
0

try this

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.