动态键/值形式反应角5

时间:2018-02-20 17:08:55

标签: angular forms angular-reactive-forms

我搜索了很长时间,但我没有找到我想做的事情。我想用角度5和反应形式添加动态键/值。

当我点击“添加参数”按钮时,动态显示2个输入。一个用于键,另一个用于值。

当我提交表格时,我希望得到这个:

{ 设置:{    key1:value1,    key2:value2 ...... } }

这就是我所做的:

我的组件:

        constructor(
        protected fb: FormBuilder,

    ) {

        // form init
        this.testForm = fb.group({
            'name': fb.control('', [Validators.required]),
            'desc': fb.control('', [Validators.required]),
            'config': fb.array([])
        });
    }
    
    
    ...

getControls(frmGrp: FormGroup, key: string) {
    return (<FormArray>frmGrp.controls[key]).controls;
}
    
 
    addConfigBlock() {

        let settingBlock = this.testForm.get('setting') as FormArray;

        settingBlock.push(this.fb.group({key: '', value: ''}));


    }

template.html

                <div fxLayout="column" fxflex="100%" class="form-standard">
                    <div formArrayName="config" *ngFor="let setting of getControls(testForm, 'config'); let i = index;">
                        <div [formGroupName]="i" fxLayout="column" fxFlex="100%"> 
                            <mat-form-field class="form-input"> 
                                <input matInput formControlName="key" name="key" maxlength="255"
                                placeholder="Key" required> 
                            </mat-form-field>
                            <mat-form-field class="form-input"> 
                                <input matInput formControlName="value" name="value" maxlength="255"
                                    placeholder="Value" required> 

                            </mat-form-field>
                        </div>
                    </div>
                </div>
                <mat-card-content class="mat-card-content">
                    <div fxLayout="row" fxLayoutAlign="start stretch" class="form-standard">
                        <div fxFlex.gt-md="100" fxFlex.xs="100">
                            <div fxLayoutAlign="space-around stretch">
                                <button type="button" mat-raised-button color="primary" (click)="addSetting()">Add setting</button>
                            </div>
                        </div>
                    </div>
                </mat-card-content>

我不知道实现这一目标的最佳途径是什么。非常感谢你:))

2 个答案:

答案 0 :(得分:0)

我看待它的方法是在组件中使用一个跟踪索引的变量,在每次添加时,增加变量。然后在表单控件的命名中使用该值,如...

i = 0;

addConfigBlock() {
  let settingBlock = this.testForm.get('config') as FormArray;
  settingBlock.push(this.fb.group({['key'+this.i] : '', ['value'+this.i]: '' }));
  this.i++;
}

并在模板中使用

标记formcontrols
formControlName="key{{i}}"
formControlName="value{{i}}"

其中i是迭代中的索引。

这是

StackBlitz

答案 1 :(得分:0)

我曾经想动态添加一个控件,但确切地知道我想添加哪个控件。发生这种情况是因为我想将所有控件值保存在后端的数组中,而不是单独列出它们。这是一个解决方案:

<form [formGroup]="myForm">
  <div formArrayName="myArray">
    <div [formGroup]="getControl('my_known_control_name')">
      <mat-checkbox formControlName="value">My known control name</mat-checkbox>
    </div>
    <div [formGroup]="getControl('my_second_known_control_name')">
      <mat-checkbox formControlName="value">My second known control name</mat-checkbox>
    </div>
  </div>
</form>
// reactive device form
myForm!: FormGroup = this.fb.group({
  myArray: this.fb.array([]),
});

constructor(private fb: FormBuilder) {}

getControl(field: string): FormGroup {
  var myArray = this.myForm.get('myArray') as FormArray | null;
  var existingControl = myArray?.controls.find(c => c.value["name"] === field);
  if (existingControl) {
    return existingControl as FormGroup;
  } else {
    var newControl = this.fb.group({
      name: field,
      value: undefined,
    });
    myArray?.push(newControl);
    return newControl;
  }
}