将数据添加到动态创建的字段

时间:2019-10-25 13:31:59

标签: javascript angular typescript

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

component.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>

1 个答案:

答案 0 :(得分:0)

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