1

Can someone explain to me why my ngIf is not working when it should be activating when the pattern error occurs?

<div>
   <form #myForm="ngForm">
      <h1>Angular Calculator</h1>

      <h4>Sum:</h4>
      <input [(ngModel)]='add1' type="text" name="add1" size="5" pattern="^(0-9)*(/.(0-9)+)?$" required> +
      <input [(ngModel)]='add2' type="text" name="add2" size="5" pattern="^(0-9)*(/.(0-9)+)?$" required>

      <p *ngIf="add1?.errors?.pattern">
         Only numeric characters allowed</p>
      <p *ngIf="add2?.errors?.pattern">
         Only numeric characters allowed</p>
      &nbsp;
      <button (click)='CalcAdd()'>
         =
      </button>
   </form>
</div>

1 Answer 1

1

use 'myForm' object for showing the error messages. I have changed in the code ngIf condition. see the working example on stackblitz

Here is the changed code.

  <div>
  <form #myForm="ngForm">
  <h1>Angular Calculator</h1>

  <h4>Sum:</h4>
  <input [(ngModel)]='add1' type="text" id="add1" name="add1" size="5" pattern="^(0-9)*(/.(0-9)+)?$"   required/> + <input [(ngModel)]='add2' type="text" name="add2"  size="5" pattern="^(0-9)*(/.(0-9)+)?$" required>

  <p *ngIf="myForm.controls.add1?.errors?.pattern">
      Only numeric characters allowed</p>
  <p *ngIf="myForm.controls.add2?.errors?.pattern">
      Only numeric characters allowed</p>
  &nbsp;
  <button (click)='CalcAdd()'>
    =
  </button>
  </form>
  </div>
Sign up to request clarification or add additional context in comments.

10 Comments

Thanks for the help. The error shows even if I enter in a valid character - is there something wrong with my pattern?
do you want only numeric in the textbox or decimal values?
Either numeric or decimals should be valid.
try to use this pattern [0-9\.]+$ and I have updated the code, which only accepts numeric.
That works! Thank you! If it's alright I have one more question, how would I add to the ngIF to disable the button when the error occurs?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.