Skyvory
Skyvory

Reputation: 373

Angular2 can't use ngModel in form repeated by ngFor

How can I use ngModel for inputs across multiple forms that's repeated by ngFor?

Angular2 gives me error when I'm trying to do so.

Error: Permission denied to access property "rejection"

Example block of problematic code:

<div *ngFor="let item of items">
    <form name="itemForm">
        {{item.name}}<input [(ngModel)]="item.name">
    </form>
</div>

Here is the plunker https://plnkr.co/edit/YNZiCBeyqJoxO5ox5nlC?p=preview

If I remove the form tag, it all run without problem, but I need it so I can use enter key on all input to update corresponding data in their own form.

Upvotes: 0

Views: 1777

Answers (2)

Lars
Lars

Reputation: 2485

As pointed out by @ranakrunal9 you can use a unique name attribute for your input. Here the code:

<div *ngFor="let item of items; let index=index">
    <form name="itemForm">
        {{item.name}}<input [(ngModel)]="item.name" name={{index}}>
    </form>
</div>

Upvotes: 0

ranakrunal9
ranakrunal9

Reputation: 13558

If ngModel is used within a form tag, either the name attribute must be set or the form control must be defined as 'standalone' in ngModelOptions.

Below will work without any error :

<div *ngFor="let item of items">
  <form name="itemForm">
    {{item.name}}<input [(ngModel)]="item.name" [ngModelOptions]="{standalone: true}">
  </form>
</div>

Upvotes: 2

Related Questions