首页 > 解决方案 > 将数据添加到动态创建的字段

问题描述

我正在使用响应式表单来动态添加一些字段并在选择框中显示数据(数组格式的 api 响应),到目前为止,我正在获取表单中的值,但无法设置为选择框。请纠正我我是反应形式的新手。

组件.ts

ngOnInit() {
    this.dynamicForm = this.formBuilder.group({
        attributes: new FormArray([])
    });
}
get f() { return this.dynamicForm.controls; }
get a() { return this.f.attributes as FormArray; }
 addAttitubute(){
    let array=[] 
    this.attributeService.getAttributes().subscribe(response =>{
       response.forEach(value =>{
      array.push(value.name);
       })
       this.a.push(this.formBuilder.group({
        attribute: this.formBuilder.array(array),
        value: this.formBuilder.array([])
    }));
    })

    console.log(this.a);

}

html

<label>
<div *ngFor="let t of a.controls; let i = index"  class="field-heading">Attribute (e.g. Colour)
        <div [formGroup]="t" >
        <select formControlName="attribute"  required class="attr-dropdown">
          <option *ngFor="let value of attribute">
            {{ value }}
          </option>
        </select>

      </div>
      <div class="flex-one">
        <label>
          <div class="field-heading">Value (e.g. Red, Blue, Green)</div>

          <p-chips inputStyleClass="full-width theme-input" ></p-chips>
        </label>
      </div>
      </div>

</label>

标签: javascriptangulartypescript

解决方案


您需要将属性和 selectedAttribute 分开。属性用于保存响应 Api 中的值,该值是初始复选框数组值。SelectedAttribute 用于从用户选择中获取选定的值。


推荐阅读