Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How validate dynamic formgroup input in angular

I have created dynamic formGroup in angular material table. Each row has one input field and add to cart & remove button. Button should be disabled in each row if that particular row’s input is invalid. Please let me know where I made the mistake.

Source code: Demo

Image:
sample UI

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

html:

<form [formGroup]="productForm">
   <table
      mat-table
      formArrayName="productsArray"
      [dataSource]="tableDetails"
      multiTemplateDataRows
      matSort
      >
      <ng-container matColumnDef="date">
         <mat-header-cell *matHeaderCellDef mat-sort-header>
            Product Date
         </mat-header-cell>
         <mat-cell *matCellDef="let row">
            {{ row.value.date | date: 'dd-MMM-yyyy' }}
         </mat-cell>
      </ng-container>
      <ng-container matColumnDef="expandedDetail">
         <mat-cell
         *matCellDef="let child; let rowindex = dataIndex"
         [attr.colspan]="tableColumns.length"
         [formGroupName]="tableDetails.data.indexOf(child)"
         >
         <div class="col-sm-6 mt-3">
            <div class="row pb-1">
               <h6>Input 2</h6>
               <textarea
                  formControlName="input2"
                  ></textarea>
            </div>
            <button [disabled]="productForm.invalid" (click)="addCart()">
            add to cart
            </button>
            <button>remove</button>
         </div>
         </mat-cell>
      </ng-container>
      <mat-header-row *matHeaderRowDef="tableColumns"></mat-header-row>
      <mat-row
         matRipple
         *matRowDef="let child; columns: tableColumns"
         class="element-row"
         ></mat-row>
      <mat-row
         *matRowDef="let row; columns: ['expandedDetail']"
         style="overflow: hidden"
         ></mat-row>
   </table>
</form>

>Solution :

Access FormGroup inside formArray using index then check invalid on that formGroup.

<button [disabled]="productForm.get('productsArray').at(tableDetails.data.indexOf(child)).invalid" (click)="addCart()">
                add to cart
</button>

ForkedExample

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading