1

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"

4
  • Your creating an empty array newItem and you're never adding items to this array. So newItem[i] will always be undefined. Commented Jan 11, 2019 at 22:51
  • Hi @fridoo, thanks for your reply, is there a way around this as I could have 3, 4 forms Commented Jan 11, 2019 at 22:53
  • 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. Commented Jan 11, 2019 at 22:56
  • @user3057745, if you make a *ngFor="let guestListItem of guestListItems", Why do you not [(ngModel)]="guestListItem.name" ?? Commented Jan 12, 2019 at 12:44

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.