0

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.

rankery
  • 307
  • 1
  • 5
  • 14
  • 1
    Not at computer to provide example but you could use a form builder to construct formarray of formarrays. So component would have `constructor(private fb: FormBuilder) { this.formGroup = this.fb.group({ rowArray: this.fb.array([]) })` and push formarrays to get what you need. – Andrew Allen Jun 30 '19 at 23:50
  • 1
    @AndrewAllen, you needn't create formGroup, you can use formArray of FormArray – Eliseo Jul 01 '19 at 06:35

1 Answers1

4

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>
Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
Eliseo
  • 50,109
  • 4
  • 29
  • 67