Ionic 4-Angular 6 formArrayName无法按预期工作

时间:2018-10-01 13:54:43

标签: angular angular-reactive-forms ionic4

尝试将formArrayName与离子复选框结合使用 这是我的控件:

this.planGroup = this.formBuilder.group({
        ...
        PlanEmails: this.formBuilder.array([
            this.formBuilder.group({
                PlanId: '',
                EmailId: ''
            })
        ]),
    });

这是我的HTML

         <ion-row>
            <ion-col formArrayName="PlanEmails" [sizeXs]="12" [sizeSm]="6" *ngFor="let email of emails">
              <ion-item>
                <ion-label>{{email.Title}}</ion-label>
                <ion-checkbox formControlName="EmailId" color="secondary" [value]="email.Id" slot="start"></ion-checkbox>
              </ion-item>
            </ion-col>
          </ion-row>

这是我遇到的错误

 ERROR Error: Cannot find control with path: 'PlanEmails -> EmailId'
    at _throwError (forms.js:1732)
    at setUpControl (forms.js:1640)
    at FormGroupDirective.push../node_modules/@angular/forms/fesm5/forms.js.FormGroupDirective.addControl (forms.js:4454)
    at FormControlName.push../node_modules/@angular/forms/fesm5/forms.js.FormControlName._setUpControl (forms.js:4959)
    at FormControlName.push../node_modules/@angular/forms/fesm5/forms.js.FormControlName.ngOnChanges (forms.js:4909)
    at checkAndUpdateDirectiveInline (core.js:9246)
    at checkAndUpdateNodeInline (core.js:10514)
    at checkAndUpdateNode (core.js:10476)
    at debugCheckAndUpdateNode (core.js:11109)
    at debugCheckDirectivesFn (core.js:11069)

试图将formArrayName移到ion-rowion-item上,但这没用。
我不知道我做错了。尝试阅读Angular文档,但我似乎无法弄清楚。

2 个答案:

答案 0 :(得分:4)

您应定义EmailId控件的正确路径。

您在FormArrayFormGroup中有FormControl个,但是在模板中定义了FormArray个中的FormControl个。

要修复此问题,您应该使用formGroupName指令。

<ion-col ... *ngFor="let email of emails; let i = index">
                                             ||
                                             \/
                                         add this
    <ion-item [formGroupName]="i">
                         ||
                         \/
                       and this

答案 1 :(得分:0)

FromGroup的例子很少。请遵循以下网址https://angular.io/guide/reactive-forms