Search code examples
angularangular-materialangular-validationangular-formbuilder

Dynamic validation FormArray of FormGroup in mat-table not works


I have FormGroup in FormArray. Form creates empty, and user filling it. User can edit fields right in a mat-table, but validations is not working if user enter wrong value (validations works only once, in a moment of pushing row). I did an example in stackblitz How can i do dynamically validate all form, and the fields in each row, with output labels something like "wrong value" under the field?


Solution

  • You're using [(ngModel)], that's good for template driven forms, with validation rules in the template itself. If you want a model-driven form, you must tie the template to the form and form controls, sth more or less like that:

    <table mat-table [dataSource]="myForm.controls.tableFields.value" [formGroup]="myForm">
    <!-- ... -->
      <ng-container matColumnDef="product_count" [formGroupName]="'tableFields'">
        <th mat-header-cell *matHeaderCellDef>Count</th>
          <td mat-cell *matCellDef="let row; let i = index" [formGroupName]="i">
            <input [formControlName]="'product_count'" />