0

I am trying to build a Form in Angular so that a user can enter numbers in a table. The number of rows and columns can be different (nRows, nColumns) but not editable by the user. The expected result should be something like this: Table Form

For the rows I am using a FormArray and ngFor is working. But I can not iterate over the Columns. Maybe my approach is not good anyway?

// transport-form.component.ts
export class TransportFormComponent implements OnInit {

  title = 'formarray';
  kostenForm!: FormGroup;
  rows!: FormArray;
  nRows = 3;
  nColumns = 3;
  constructor(private formBuilder: FormBuilder) {}
  ngOnInit() {
    this.kostenForm = new FormGroup({
      rows: new FormArray([]),
    });
    for (let i = 0; i < this.nRows; i++) {
      this.addItem();
    }
  }
  createItem(): FormGroup {
    let row = {};
    for (let j = 0; j < this.nColumns; j++) {
      row[`v${j}`] = '';
    }
    return this.formBuilder.group(row);
  }
  addItem(): void {
    this.rows = this.kostenForm.get('rows') as FormArray;
    this.rows.push(this.createItem());
  }
}

// transport-form.component.html
<div [formGroup]="kostenForm">  
<div formArrayName="rows"  
  *ngFor="let row of kostenForm.get('rows')['controls']; let i = index;">  
  <div [formGroupName]="i">  
    <!-- <ng-container *ngFor="let control of row.controls; let j = index">
    <input formControlName="v{j}">??? 
</ng-container> Does not work -->
<!-- Workaround to demonstrate expected output: -->
    <input formControlName="v0">  
    <input formControlName="v1">  
    <input formControlName="v2">  
  </div>  
</div>  
</div>  
{{ kostenForm.value | json }}

1 Answer 1

0

I can't comment due to my low reputation, so I add an answer.

Long story short, if you have an Array of Array, you can create a FormArrays of FormArrays.

You can find all the explanations in the accepted answer of this post:

Angular-FormArray: Creating a table form from 2-dimensional Javascript array

In the post he use a 2x2 data array, but I think you can adapt it to your needed.

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

1 Comment

Thx I tried this example first but the code from stackblitz gives me an error: "property 'controls' does not exist on type 'AbstractControl"

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.