亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 Angular 10 中修補動態表單數組的值?

如何在 Angular 10 中修補動態表單數組的值?

慕工程0101907 2023-07-20 14:58:42
我有一個動態 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.. 錯誤
查看完整描述

1 回答

?
楊__羊羊

TA貢獻1943條經驗 獲得超7個贊

問題似乎 patchValue 無法填充表單數組。您可以使用push()像常規數組一樣填充表單數組。


假設您的 this.qualificationData 是一個包含許多“expertsQualification”(數組類型)的數組,并且類/接口 ExpertsQualification 具有屬性“school”、“level”、“specialization”和“passed_year”,您可以執行以下操作:


(this.educationAndExperienceForm.controls.educationForm as FormArray).reset(); //reset the FormArray


this.qualificationData.forEach(x => {

    (this.educationAndExperienceForm.controls.educationForm as FormArray)

    .push(this.fb.group({

        school: [x.school, Validators.required],

        degree: [x.degree, Validators.required],

        specialization: [x.specialization, Validators.required],

        passed_year: [x.passed_year, Validators.required]

    });

};

..這樣您就可以循環遍歷數組,并為每個元素將表單組推送到表單數組。請注意,將其轉換為 FormArray 非常重要,例如


(this.educationAndExperienceForm.controls.educationForm as FormArray)

如果你不這樣做,它將保留為 AbstractControl,并且你將無法使用數組函數,如推、拉等。


查看完整回答
反對 回復 2023-07-20
  • 1 回答
  • 0 關注
  • 175 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號