修补动态数据以按角度形式重复键入

时间:2019-04-11 10:44:15

标签: javascript angular typescript angular-reactive-forms angular-formly

我的目标是将外部json数据修补到包含FieldArrayType的表单中。

说我有以下正式的字段配置:

fields: FormlyFieldConfig[] = [
    {
      key: 'cars',
      type: 'repeat',
      fieldArray: {
        fieldGroupClassName: 'row',
        templateOptions: {
          btnText: 'Add',
        },
        fieldGroup: [
          {
            className: 'col-sm-4',
            type: 'input',
            key: 'type',
            templateOptions: {
              label: 'Type:'
            },
          },
          {
            type: 'input',
            key: 'name',
            className: 'col-sm-3',
            templateOptions: {
              label: 'Name:'
            },
          },
        ],
      },
    },
  ];

然后我想将一些数据打补丁到这种重复类型:

  patchData() {
    let data = {
      "cars":[
        {"type":"Type1","name":"Name1"},
        {"type":"Type2","name":"Name2"}]
      };

    // Failure: Only the first car value is patched, the second car is not patched
    // (unless) 'Add' is clicked first, which is not intended.
    this.form.patchValue(data);
  }

问题在于,在表单的初始加载中,重复部分中仅存在一项。因此,如果我将数据修补到包含两个或两个以上字段数组项的表单,则仅将第一项应用并存储在模型中。

是否有一种方法可以在修补数据之前以编程方式向FieldArray添加项目,以便模型接收数据?

注意:数据的长度可以变化。

请参阅以下堆栈闪电示例: https://stackblitz.com/edit/angular-vfykhx

1 个答案:

答案 0 :(得分:0)

  constructor(
       private fb: FormBuilder
     )
     
     patchData() {
      this.form=this.fb.group({
        cars:this.fb.array([])
      });
      
        let data = {
          "cars":[
            {"type":"Type1","name":"Name1"},
            {"type":"Type2","name":"Name2"}]
          };
        const fa = <FormArray>this.form.controls['cars'];
        data.cars.forEach((each)=>{
          let tFormGroup:FormGroup=this.fb.group({
            type:[each.type],
            name:[each.name]
          });
          tFormGroup.patchValue(each);
          fa.push(tFormGroup);
        })
      }
    <form [formGroup]="form">
      <div formArrayName="cars">
        <div *ngFor="let car of form['controls'].cars;let i=index;" [formGroupName]="i">
          <input ype="text" formControlName="type">
           <input ype="text" formControlName="name">
        </div>
      </div>
    </form>