我试图将多维数组显示为表单。我希望能够指定x列和y行的值。
我不确定在输入框的formControlName中放入什么
Plunker:https://plnkr.co/edit/mfUquLwCR0lI7vUiAUBe?p=preview
代码:
<div class="jumbotron">
<legend>Settings</legend>
<form [formGroup]="settingsForm" class="form-horizontal">
<fieldset>
<div formArrayName="thresholdArray">
<div class="row" *ngFor="let y_row of settingsForm.controls.thresholdArray.controls; let y = index" >
<div class="col-lg-3" *ngFor="let x_row of y_row.controls.threshold.controls; let x = index" [formGroupName]="y">
<div class="well bs-component">
<label for="inputThreshold" class="col-lg-2 control-label">({{ x }},{{ y }})</label>
<div class="col-lg-10">
<input type="text" formControlName="x" class="form-control" id="inputThreshold" placeholder="Threshold" autocomplete="off">
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<button type="submit" class="btn btn-primary btn-lg">Submit</button>
</div>
</div>
</fieldset>
</form>
</div>
打字稿/角色代码:(删除patchValues,因为它有效且不重要,你可以在plunker示例中看到它。)
import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators, FormGroup, FormArray, FormControl } from '@angular/forms';
export class SettingsComponent implements OnInit {
public settingsForm: FormGroup;
public NUMBER_OF_X_ROWS: number = 4;
public NUMBER_OF_Y_ROWS: number = 4;
public thresholdArray = [];
public scaleMin;
public scaleMax;
constructor(public fb: FormBuilder) { }
ngOnInit() {
this.initValues();
this.buildForm();
var settingsValues = {
scaleMin: this.scaleMin,
scaleMax: this.scaleMax,
thresholdArray: this.thresholdArray
}
this.patchValue(this.settingsForm, settingsValues);
console.log(this.settingsForm)
}
initValues() {
let x: number;
let y: number;
if (localStorage.getItem('scaleMin') === null) {
this.scaleMin = -140000;
localStorage.setItem('scaleMin', this.scaleMin);
} else {
this.scaleMin = localStorage.getItem('scaleMin');
}
if (localStorage.getItem('scaleMax') === null) {
this.scaleMax = -90000;
localStorage.setItem('scaleMax', this.scaleMax);
} else {
this.scaleMax = localStorage.getItem('scaleMax');
}
if (localStorage.getItem('thresholdArray') === null) {
console.log("Initializing thresholdArray");
for (y = 0; y < this.NUMBER_OF_Y_ROWS; y++) {
let tempArray = [];
//this.thresholdArray[y] = [];
for (x = 0; x < this.NUMBER_OF_X_ROWS; x++) {
tempArray.push(-102000)
}
this.thresholdArray[y] = { 'threshold': tempArray }
}
localStorage.setItem('thresholdArray', JSON.stringify(this.thresholdArray));
} else {
this.thresholdArray = JSON.parse(localStorage.getItem('thresholdArray'));
}
}
buildForm() {
this.settingsForm = this.fb.group({
scaleMin: [''],
scaleMax: [''],
thresholdArray: this.fb.array([
this.fb.group({
threshold: this.fb.array([
])
})
])
})
}
}