Skyvory Skyvory - 15 days ago 33
TypeScript Question

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.

Answer

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>