17

无法将值修补到 FormArray resultList

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

TS 文件:

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() {
  }
}

模型:

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

HTML:

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

这个.studList JSON:

[  
   {  
      "firstName":"santosh",
      "lastName":"jadi",
      "gender":"male",
      "dob":"2018-03-31T18:30:00.000Z",
      "qualification":"BE"
   },
   {  
      "firstName":"santosh",
      "lastName":"jadi",
      "gender":"male",
      "dob":"2018-03-31T18:30:00.000Z",
      "qualification":"BE"
   }
]
4

6 回答 6

22

根据您的问题,您想添加新StudentresultList. 首先,您需要知道AbstractControlFormArray是一个数组 。您可以仅将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()样板,这些样板可以构建成更大的形式。

此外,在绑定到元素的 html formControlName<p>中,它不是输入,您不能绑定到非表单元素,例如div/p/span ...:

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

修补值

修补阵列时要小心。因为FormArraypatchValue按索引修补值:

 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 演示

于 2018-04-14T15:35:50.890 回答
6

首先尝试执行此步骤并确保您使用正确的方式

因为在您的场景中,您正在将对象修补到 formArray,所以您必须先解析该对象并检查您是否在 app.module.ts 中导入了 ReactiveFormsModule。

于 2018-04-16T10:03:31.003 回答
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);
  }
于 2018-04-10T12:31:37.007 回答
3

我更喜欢使用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([])
        });
    }
}

我相信 studlist 将通过 API 调用作为可观察而不是静态数组获得。假设,我们的数据如下。

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,

        }));
    });
}
于 2018-11-13T16:33:59.227 回答
2

数组不包含patchValue方法。您必须分别迭代控件和patchValue 每个控件。

于 2018-04-08T08:35:47.067 回答
0

我将formgroupinformarray用作:

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)])
          }))
        });

使用这种方法,我们也可以验证嵌套字段。

希望这可能会有所帮助。

于 2019-09-26T15:35:32.857 回答