1

I'd like to make certain input-fields only available for integer or decimal-values. So I got the following code:

<input type="text" pattern="[0-9]*" [(ngModel)]="myValue" pInputText class="medium-field"
    (change)="calculate()"/>

So this field is marked if the pattern does not match the input. Still I would like to disable the submit-button while the pattern is not matched. Can I somehow access that value as a boolean or is there another way?

1
  • Easiest way is probably to use Reactive Forms in Angular; but explaining what those are is probably beyond the scope of answering a question. An alternate way would be to trigger a buttonDisabled flag in your calculate function that controls whether your button is disabled or not. Commented Dec 27, 2018 at 0:52

3 Answers 3

3

If you don't want to use Reactive Forms, you can do:

<input type="text" pattern="[0-9]*" [(ngModel)]="myValue" #myInput />
<button [disabled]="!myInput.validity.valid">Submit</button>

That will disable your submit button if the HTML validity of your input is invalid.

Here is a working example.

I would also suggest you use type="number" in your input.

Sign up to request clarification or add additional context in comments.

Comments

1

The form will be marked automatically as invalid if your input didn't matched with your pattern.

You can just use:

<form novalidate
      #form="ngForm">

     /* Your inputs */

     <button type="button"
             [disabled]="form.invalid">     // form as per the referenced #form="ngForm"
                                            // Disables if your inputs are invalid or doesn't meet with its pattern
         Submit
     </button>

Comments

1

try form validation for it.using *ngIf and

<button type="submit" [disabled]="form.invalid">SEND</button>

Comments

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.