无法将数据修补到FormArray

时间:2018-04-08 08:19:06

标签: javascript html angular typescript formarray

无法将值修补为FormArray Traceback (most recent call last): File "<pyshell#413>", line 2, in <module> sql_stmt = sql_stmt + ("dumm5('%s' , '%s')" ,(key,adict1[key])) TypeError: must be str, not tuple

任何人都可以解释我,我错过了什么?

TS文件:

resultList

型号:

import { Component, OnInit } from '@angular/core';
import { Student } from '../student';
import { FormGroup, FormControl, Validators, FormArray } from '@angular/forms';

@Component({
  selector: 'app-container',
  templateUrl: './container.component.html',
  styleUrls: ['./container.component.css']
})

export class ContainerComponent implements OnInit {

  studList: Student[] = [];
  myform: FormGroup = new FormGroup({
    firstName: new FormControl('', [Validators.required, Validators.minLength(4)]),
    lastName: new FormControl(),
    gender: new FormControl('male'),
    dob: new FormControl(),
    qualification: new FormControl(),
    resultList: new FormArray([])
  });    

  onSave() {
    let stud: Student = new Student();
    stud.firstName = this.myform.get('firstName').value;
    stud.lastName = this.myform.get('lastName').value;
    stud.gender = this.myform.get('gender').value;
    stud.dob = this.myform.get('dob').value;
    stud.qualification = this.myform.get('qualification').value;
    this.studList.push(stud);
    this.myform.controls.resultList.patchValue(this.studList);
    console.log(JSON.stringify(this.studList));
  }

  ngOnInit() {
  }
}

HTML:

export class Student {
    public firstName: String;
    public lastName: string;
    public gender: string;
    public dob: string;
    public qualification: string;
}

this.studList JSON:

    <div class="container">
        <h3>Striped Rows</h3>
        <table class="table table-striped" formArrayName="resultList">
            <thead>
                <tr>
                    <th>Firstname</th>
                </tr>
            </thead>
            <tbody>
                <tr *ngFor="let item of myform.controls.resultList.controls; let i = index" [formGroupName]="i">
                    <td><p formControlName="firstName"></p></td>
                </tr>
            </tbody>
        </table>
    </div>

6 个答案:

答案 0 :(得分:11)

根据您的问题,您要将新Student添加到resultList。 首先,您需要知道FormArray AbstractControl 的数组。 您可以添加到仅限数据类型 AbstractControl 而不是其他类型。 要简化任务,请使用FormBuilder

 constructor(private fb: FormBuilder) {}

  createForm() {

    this.myform = this.fb.group({
      firstName: ['', [Validators.required, Validators.minLength(4)]],
      lastName: [],
      gender: ['male'],
      dob: [],
      qualification: [],
      resultList: new FormArray([])
    });
  }

正如您在填写 resultList FormArray之前所看到的那样,它已映射到 FormGroup

onSave() {
    let stud: Student = new Student();
    stud.firstName = 'Hello';
    stud.lastName = 'World';
    stud.qualification = 'SD';
    this.studList.push(stud);

    let studFg = this.fb.group({
      firstName: [stud.firstName, [Validators.required, Validators.minLength(4)]],
      lastName: [stud.lastName],
      gender: [stud.gender],
      dob: [stud.dob],
      qualification: [stud.qualification],
    })
     let formArray = this.myform.controls['resultList'] as FormArray;
    formArray.push(studFg);
    console.log(formArray.value)
  }
  

FormBuilder - 根据用户指定创建 AbstractControl   配置。

     

基本上是语法糖缩短新FormGroup(),   新的FormControl()新的FormArray()样板可以构建   以更大的形式。

此外,在绑定到<p>元素的html formControlName 中,它不是输入,您无法绑定到不形成 div /的元素p /跨度 ...

 <tbody>
                <tr *ngFor="let item of myform.controls.resultList.controls; let i = index" [formGroupName]="i">
                    <td><p formControlName="firstName"></p></td> <==== Wrong element 
                </tr>
</tbody>

所以,我想你只是想在表中添加学生。然后迭代 studList 并在表格中显示它的值:

<tbody>
                <tr *ngFor="let item of studList; let i = index" [formGroupName]=i>
                    <td>
                        <p> {{item.firstName}} </p>
                    </td>
                </tr>
</tbody>

修补值

修补阵列时要小心。由于 FormArray patchValue通过索引修补值:

 patchValue(value: any[], options: {onlySelf?: boolean, emitEvent?: boolean} = {}): void {
    value.forEach((newValue: any, index: number) => {
      if (this.at(index)) {
        this.at(index).patchValue(newValue, {onlySelf: true, emitEvent: options.emitEvent});
      }
    });
    this.updateValueAndValidity(options);
  }

因此,下面的代码会修补 index = 0 处的元素:this.myform.controls['resultList'] as FormArray的第一个索引值将替换为:

let stud1 = new Student();

stud1.firstName = 'FirstName';
stud1.lastName = 'LastName';
stud1.qualification = 'FFF';
formArray.patchValue([stud1]);

您的情况不起作用,因为patchValue 需要数组中的某些控件。在您的情况下,数组中没有控件。看源代码。

StackBlitz Demo

答案 1 :(得分:6)

First try with this steps and make sure are you on correct way

因为在您的场景中,您正在将对象修补为formArray,因此您必须首先解析该对象。检查一下你是否在app.module.ts中导入了ReactiveFormsModule。

答案 2 :(得分:4)

你必须像这样,代码取自angular.io,你需要做setcontrol,它会做或者通过链接有相同的代码,它使用地址数组

 this.setAddresses(this.hero.addresses);

  setAddresses(addresses: Address[]) {
    const addressFGs = addresses.map(address => this.fb.group(address));
    const addressFormArray = this.fb.array(addressFGs);
    this.heroForm.setControl('secretLairs', addressFormArray);
  }

答案 3 :(得分:2)

我更喜欢使用FormBuilder创建表单。

export class ComponentName implements OnInit {
    form: FormGroup;
    constructor(private fb: FormBuilder){}

    ngOnInit() {
       this.buildForm();
    }

    buildForm() {
        this.form = this.fb.group({
            firstName: '',
            lastName: '',
            ...
            resultList: this.fb.array([])
        });
    }
}

我认为,可通过API调用以可观察的方式而不是静态的数组形式来获取studlist。假设,我们的数据如下。

resultModel = 
{
    firstName: "John",
    lastName: "Doe",
    ....
    resultList: [
       {
            prop1: value1,
            prop2: value2,
            prop3: value3
       },
       {
            prop1: value1,
            prop2: value2,
            prop3: value3
       }
       ...
    ]
}

一旦数据可用,我们可以按如下所示修补值:

patchForm(): void {
        this.form.patchValue({
            firstName: this.model.firstName,
            lastName: this.model.lastName,
            ...
        });

        // Provided the FormControlName and Object Property are same
        // All the FormControls can be patched using JS spread operator as 

        this.form.patchValue({
            ...this.model
        });

        // The FormArray can be patched right here, I prefer to do in a separate method
        this.patchResultList();
}

// this method patches FormArray
patchResultList() {
    let control = this.form.get('resultList') as FormArray;
    // Following is also correct
    // let control = <FormArray>this.form.controls['resultList'];

   this.resultModel.resultList.forEach(x=>{
        control.push(this.fb.group({
            prop1: x.prop1,
            prop2: x.prop2,
            prop3: x.prop3,

        }));
    });
}

答案 4 :(得分:1)

数组不包含patchValue方法。你必须迭代控件和patchValue 他们每个人分开。

答案 5 :(得分:0)

我将formgroup中的formarray用作:

this.formGroup = new FormGroup({
      clientCode: new FormControl('', []),
      clientName: new FormControl('', [Validators.required, Validators.pattern(/^[a-zA-Z0-9 _-]{0,50}$/)]),
      type: new FormControl('', [Validators.required]),
      description: new FormControl('', []),
      industry: new FormControl('', []),
      website: new FormControl('', [Validators.required, Validators.pattern(this.settings.regex.website)]),
      businessEmail: new FormControl('', [Validators.pattern(this.settings.regex.email)]),
      clients: this._formBuilder.array([this._formBuilder.group({
        contactPerson: new FormControl('', [Validators.required]),
        contactTitle: new FormControl('', [Validators.required]),
        phoneNumber: new FormControl('', [Validators.required, Validators.pattern(this.settings.regex.phone)]),
        emailId: new FormControl('', [Validators.required, Validators.pattern(this.settings.regex.email)]),
        timeZone: new FormControl('', [Validators.required, Validators.pattern(this.settings.zipCode), Validators.minLength(5), Validators.maxLength(12)])
      })])
    })

对于补丁值,我使用以下方法:

let control = _this.formGroup.get('clients') as FormArray
        clients.forEach(ele => {
          control.push(_this._formBuilder.group({
            contactPerson: new FormControl(ele.client_name, [Validators.required]),
            contactTitle: new FormControl(ele.contact_title, [Validators.required]),
            phoneNumber: new FormControl(ele.phone_number, [Validators.required, Validators.pattern(_this.settings.regex.phone)]),
            emailId: new FormControl(ele.email_id, [Validators.required, Validators.pattern(_this.settings.regex.email)]),
            timeZone: new FormControl(ele.timezone, [Validators.required, Validators.pattern(_this.settings.zipCode), Validators.minLength(5), Validators.maxLength(12)])
          }))
        });

使用此方法,我们还可以验证嵌套字段。

希望这会有所帮助。