以 angular 形式设置键和值

Set key and value in angular form

最初我有一个简单的JSON

  jsonData = {
    status : "true",
    message: "Dynamic creation of input boxes and patch its value",
    result: [
        {
            "dataOneValue": "12cm"
        },
        {
            "dataTwoValue": "10cm"
        }
    ]
}

ngOnInit,

ngOnInit() {
  this.jsonData.result.forEach(element => {
    console.log(element);
  });

使用此 JSON,我需要创建输入框,其中键和值在 result 数组中给出..

使用上面我需要为输入框设置键和值,

所以会喜欢,

key dataOneValue => value 12cm

key dataTwoValue => value 10cm

这里我只给出了 2 只是为了理解,但它不会是静态的..,它可能会根据结果数组具有的对象数量而有所不同..

那么如何将键和值设置到 json 的 result 数组中的输入框?

Stackblitz https://stackblitz.com/edit/angular-x7mda4

也许这有帮助:

https://stackblitz.com/edit/angular-z6fuog

<form [formGroup]="form">
  <span *ngFor="let control of controls">
    <input type="text" [formControlName]="control" placeholder="dataOneValue">
  <br><br>
  </span>
</form>

ngOnInit() {  
  // firstName: ['', Validators.required],
  let _controls = {};
  this.jsonData.result.forEach(element => {
    let key = Object.keys(element)[0];    
    let control = [element[key], Validators.required];
    _controls[key] = control;
    this.controls.push(key);
    //console.log(_controls);
  });
  this.form = this.formBuilder.group(_controls);  
}

这应该通过动态构建表单来处理 Reactive 表单:

https://stackblitz.com/edit/angular-x7mda4

在app.component.ts

get resultForms() {
  return this.resultForm.get('results') as FormArray
}

ngOnInit() {
  this.resultForm = this.fb.group({
    results: this.fb.array([ ]),
  });

  this.jsonData.result.forEach(element => {
    const resultGroup = this.fb.group({
      value: element[Object.keys(element)[0]]
    })
    this.resultForms.push(resultGroup);
  });
}

在app.component.html

<form [formGroup]="resultForm">
  <div formArrayName="results">
      <div *ngFor="let result of resultForms.controls; let i=index" [formGroupName]="i">
          <input formControlName="value">
      </div>
  </div>
</form>