javascript 无法将数据修补到FormArray

qc6wkl3g  于 2023-03-28  发布在  Java
关注(0)|答案(7)|浏览(98)

无法将值修补到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;
}

超文本标记语言:

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

this.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"
   }
]
qyyhg6bp

qyyhg6bp1#

通过你的问题,你想添加新的StudentresultList。首先,你需要知道FormArrayAbstractControl的数组。你可以添加到数组中,只有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([])
    });
  }

在填充resultListFormArray之前可以看到,它Map到了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

它本质上是语法糖,缩短了new FormGroup()new FormControl()new 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>

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

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

打补丁值

打数组补丁时要注意,因为FormArray的patchValue是按index打补丁的:

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

1bqhqjot

1bqhqjot2#

First try with this steps and make sure are you on correct way
因为在您的场景中,您要将对象修补到formArray,所以您必须首先解析该对象,并检查一次是否在app.module.ts中导入了ReactiveFormsModule。

vecaoik1

vecaoik13#

你必须这样做,代码取自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);
  }
b5lpy0ml

b5lpy0ml4#

我更喜欢使用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,

        }));
    });
}
idv4meu8

idv4meu85#

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

c0vxltue

c0vxltue6#

我在formarray中使用formgroup作为:

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

使用这种方法,我们也可以验证嵌套字段。
希望这个能帮上忙。

exdqitrt

exdqitrt7#

首先根据检索到的数据结构创建表单,然后使用patchValue;
在应用patchValue之前,表单需要包含所有表单控件。
假设您数据具有包含字符串数组的属性
伪代码:

for ( const item of data.myArray ) {

  form.controls.myArray.push( new FormControl('') )

}

然后

form.patchValue(data);

这个例子没有什么意义,因为你可以直接在for循环中初始化数据,但是对于更复杂的形式,这将使你避免解析所有的键和数据类型来初始化值。

相关问题