Hassan Al Bourji
Hassan Al Bourji

Reputation: 195

Ionic 4 - Angular 6 formArrayName not working as expected

Trying to use formArrayName with a list of ionic checkboxes This is my control:

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

And this is my 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>

This is the error I'm getting

 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)

Tried moving formArrayName to ion-row and to ion-item and it didn't work.
I don't know I'm doing wrong. Tried reading Angular documentation but I can't seem to figure it out.

Upvotes: 1

Views: 2120

Answers (2)

yurzui
yurzui

Reputation: 214345

You should define correct path to EmailId control.

You have FormArray of FormGroups of FormControls but have defined FormArray of FormControls in template.

To fix it you should be using formGroupName directive.

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

Upvotes: 4

Sateesh
Sateesh

Reputation: 1336

There is few examples for FromGroup. Please follow this URL https://angular.io/guide/reactive-forms

Upvotes: 0

Related Questions