Home > Enterprise >  Angular, Init form inputs are invalid but value is valid
Angular, Init form inputs are invalid but value is valid

Time:02-08

I made an angular form with two inputs number and one select. I fill these inputs with a model values, but the two numbers inputs is invalid and i need to click inside it to change it to valid.

I use inputs like this :

<input type="text"
  name="price"
  id="price"
  [(ngModel)]="chair.price"
  formControlName="price"
  
  [ngClass]="{
      'is-invalid': editPriceForm.controls['price'].invalid,
      'is-valid':editPriceForm.controls['price'].valid
   }"
/>

So in the initial render form, i get the good value in the inputs but the class of the input is 'is-invalid', and i don't know why. I try to trigget a markAllAsTouched but nothing change.

When i click inside the input, and click out, the class change to become valid.

Do you know if something is possible to tell to the form to be rechecked after filling data ?

CodePudding user response:

This happens because the code is always executing, without checking if the user made any changes for it to check. What you should do is the following:

    <input type="text"
      name="price"
      id="price"
      [(ngModel)]="chair.price"
      formControlName="price"
      
      [ngClass]="{
                  'is-invalid': editPriceForm.controls['price'].invalid && 
                                editPriceForm.controls['price'].touched
                  }"
    />

With what I added that was editPriceForm.controls['price'].touched the code is only executed if the user clicked on the input

CodePudding user response:

You are mixing two different types of Angular's handling of forms. First, refactor your code to either Template Driven Forms by removing formControlName and only using [(ngModel)] or by removing [(ngModel)] and only use formControlName so that your code is Reactive Forms.

  •  Tags:  
  • Related