如何在 Angular 10 中修补动态表单数组的值?

我有一个动态 formArray,保存数据,一切工作正常,但我在修补值时遇到问题,而且我在网上找不到任何确切的解决方案。


下面是代码,


    <form [formGroup]="educationAndExperienceForm">

        <div formArrayName="educationForm">

            <div *ngFor="let education of educationAndExperienceForm.controls.educationForm['controls'];let i = index;"

                [formGroupName]="i">

                <h6 class="text-left circularBold" *ngIf="i == 0"><b>Highest Qualification</b></h6>

                <input type="text" class="education-inputs w-100 mt-3" placeholder="School/College/University"

                    formControlName="school"

                    [ngClass]="{ 'input-error': submitted && educationAndExperienceForm.controls.educationForm.controls[i].invalid }">

                <input type="text" class="education-inputs w-100 mt-3" placeholder="Degree Ex: Master's"

                    formControlName="degree"

                    [ngClass]="{ 'input-error': submitted && educationAndExperienceForm.controls.educationForm.controls[i].invalid }">

                <input type="text" class="education-inputs w-100 mt-3"

                    placeholder="Field of Education Ex: Computer Science" formControlName="specialization"

                    [ngClass]="{ 'input-error': submitted && educationAndExperienceForm.controls.educationForm.controls[i].invalid }">

                <div class="text-left">

                    <input type="text" class="education-inputs w-100 mt-3" placeholder="Graduate Year"

                        formControlName="passed_year"

                        [ngClass]="{ 'input-error': submitted && educationAndExperienceForm.controls.educationForm.controls[i].invalid }">

                </div>


对于我使用的第一种方式,我收到无法使用 forEach.. 错误


慕工程0101907
浏览 126回答 1
1回答

杨__羊羊

问题似乎 patchValue 无法填充表单数组。您可以使用push()像常规数组一样填充表单数组。假设您的 this.qualificationData 是一个包含许多“expertsQualification”(数组类型)的数组,并且类/接口 ExpertsQualification 具有属性“school”、“level”、“specialization”和“passed_year”,您可以执行以下操作:(this.educationAndExperienceForm.controls.educationForm as FormArray).reset(); //reset the FormArraythis.qualificationData.forEach(x => {&nbsp; &nbsp; (this.educationAndExperienceForm.controls.educationForm as FormArray)&nbsp; &nbsp; .push(this.fb.group({&nbsp; &nbsp; &nbsp; &nbsp; school: [x.school, Validators.required],&nbsp; &nbsp; &nbsp; &nbsp; degree: [x.degree, Validators.required],&nbsp; &nbsp; &nbsp; &nbsp; specialization: [x.specialization, Validators.required],&nbsp; &nbsp; &nbsp; &nbsp; passed_year: [x.passed_year, Validators.required]&nbsp; &nbsp; });};..这样您就可以循环遍历数组,并为每个元素将表单组推送到表单数组。请注意,将其转换为 FormArray 非常重要,例如(this.educationAndExperienceForm.controls.educationForm as FormArray)如果你不这样做,它将保留为 AbstractControl,并且你将无法使用数组函数,如推、拉等。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript