简体   繁体   中英

Add data to dynamically created fields

I am using reactive forms to dynamically add some fields and show the data (api response in array format) in select boxes, so far I'm getting the values in form but not able to set to the select boxes. please correct me I am new to reactive forms.

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>

You need to separate the attribute and selectedAttribute. Attribute uses to save values from response Api which was inited checkbox arrays value. SelectedAttribute uses to get selected value from user select.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM