Search code examples
htmlangularvalidationngfor

Check if fields generated by *ngFor are valid with required flag


i have this *ngFor for some input fields,

<ng-container *ngFor="let qp of myQuoted.quoteQuantityPrice; let index = i;">
            <td>
                <input #ng_price[i]="ngModel" class="number" type="number" pattern="[1-9]*" [(ngModel)]="qp.price" required>
            </td>
        </ng-container>

and I want this button to be disables if any of the #ng_price fields doesn't follow the regex pattern doesn't have any data in it

for objects that have only one input field ever I have the button disabled like this:

 <button [disabled]= "ng_supplier.invalid || ng_inventory.invalid || ng_leadWeeks.invalid || ng_multOrderQty.invalid || ng_minOrderQty.invalid" (click)="Save()">Save</button>

I want to add ng_price.invalid to that list of validators I tried adding ng_price.invalid in the disabled block but as I expected it doesn't really work like that and building the project ends up failing because ng_price.invalid does not exist.


Solution

  • Try this

    html

    <ng-container *ngFor="let qp of myQuoted.quoteQuantityPrice; let index = i;">
        <td>
        <form [formGroup]="formArr[i]">
            <input formControlName="app_price" class="number" type="number">
          </form>
        </td>
     </ng-container>
    

    ...

    <button [disabled]= "(formArr[i].get('app_price').touched && formArr[i].get('app_price').invalid) || ng_supplier.invalid || ng_inventory.invalid || ng_leadWeeks.invalid || ng_multOrderQty.invalid || ng_minOrderQty.invalid" (click)="Save()">Save</button>
    

    ts

        formArr: any[] = [];
        pricePattern: any = "[1-9]*" ;
    

    ...

      constructor(
        private fb: FormBuilder,
      ) {
            for (let j of this.myQuoted.quoteQuantityPrice) {
              this.formArr.push(
                this.fb.group({
                  app_price: ["", [Validators.required, Validators.pattern(this.pricePattern)]],
                })
              );
            }
       }
    

    ...