0
votes

I am working on an Angular 4 project, I currently have a *ngFor, and in the loop we are creating a new form (so I could end up with 2 or more forms)

The problem I am having is, the [(ngModel)] is not binding to the array key.

Code examples below:

Definition of the new Array:

public newItem: Array<{ category_id: number, name: string, number_of_people_invited: number, number_of_people_confirmed: number }> = [];

then the form

<div *ngFor="let guestListItem of guestListItems; let i = index;">
    <form (submit)="doSubmit(i)" [name]="i">
    <ion-row ion-list>
        <ion-col size="6">
            <ion-item lines="none">
                <ion-input name="name"
                [(ngModel)]="newItem[i].name"
                style="border: none" type="text"
                placeholder="Family name"></ion-input>
            </ion-item>
        </ion-col>
        <ion-col size="6">
            <ion-item lines="none">
                <ion-input name="number_of_people_invited"
                [(ngModel)]="newItem[i].number_of_people_invited"
                type="tel" placeholder="No. Guests"></ion-input>
                <ion-button type="submit" end>Add</ion-button>
            </ion-item>
        </ion-col>
    </ion-row>
    </form>
</div>

The error am getting is: GuestListPage.html:20 ERROR TypeError: Cannot read property 'name' of undefined

this is line 20 : [(ngModel)]="newItem[i].name"

1
Your creating an empty array newItem and you're never adding items to this array. So newItem[i] will always be undefined. - frido
Hi @fridoo, thanks for your reply, is there a way around this as I could have 3, 4 forms - Billy Mahmood
You should say what you're really trying to achieve. What type and purpose have your guestListItems? Maybe you could use those to store the input data. - frido
@user3057745, if you make a *ngFor="let guestListItem of guestListItems", Why do you not [(ngModel)]="guestListItem.name" ?? - Eliseo

1 Answers

3
votes

Your error is saying newItem[i] is undefined but your template is still trying to extract name from it. newItem[i] may be populated later, but at that point of evaluation it's still trying to pull out a value from something which is undefined, which obviously doesn't make sense.

Have you tried [(ngModel)]="newItem[i]?.name"

With the ? Angular won't evaluate newItem[i] until it is not null or undefined.

This comment sums up the ? decently.