rankery
rankery

Reputation: 317

Matrix in FormGroup [Angular 2+]

I need to create interface for generating matrix. I have two inputs like width and height and matrix of inputs that depends on width and height. My interface so u`ll understand it better

I can`t make this inputs unique so they will bind to matrix in class correctly.

So can someone share a solution for creating two-way data binded matrix and some tips will be helpful too.

I've tryed some things with FormGroup but right after i found FormArray. Sadly there isn`t something like FormMatrix.

HTML:

<p *ngFor="let itemX of createArrayAndFill(thirdData.x);">
    <mat-form-field *ngFor="let itemY of createArrayAndFill(thirdData.y);">
        <input [(ngModel)]="thirdData.matrix[itemX][itemY]" matInput name="item--{{itemX}}--{{itemY}}"
            placeholder="Значення {{itemX}} {{itemY}}" formControlName="matrixControl">
    </mat-form-field>
</p>

JS with data:

createArrayAndFill(n: number) {
    return Array(n).fill(0).map((item, i) => i)
}
thirdData = {
    x: 3, y: 3, matrix: [[1.1, 0.8, 0.9],
    [6.1, 3.2, 0.4],
    [-0.4, 0.2, 8.7]]
}

Also Angular version 7.

Upvotes: 0

Views: 1092

Answers (1)

Eliseo
Eliseo

Reputation: 57939

See stackblitz, if you want to move across the table using arrows key, see this answer in stackoverflow

TS Code:

rows=5;
cols=3;
form=new FormArray([]);

ngOnInit()
{
  for (let i = 0; i < this.rows; i++) {
      this.form.push(new FormArray([]))
      for (let j = 0; j < this.cols; j++) {
        (this.form.at(i) as FormArray).push(new FormControl())
      }
  }
}

HTML Code:

<form [formGroup]="form">
  <div *ngFor="let row of form.controls;let i=index">
    <input *ngFor="let col of row.controls" [formControl]="col">
  </div>
</form>

Upvotes: 4

Related Questions