user3953201
user3953201

Reputation: 97

Angular 2 form control without name

I'm stuck with an Angular 2 form. I want a single point to check if the whole form is valid or not, so I put all controls inside a <form> tag. This leads to an error message:

Error: 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.

  Example 1: <input [(ngModel)]="person.firstName" name="first">
  Example 2: <input [(ngModel)]="person.firstName" [ngModelOptions]="{standalone: true}">

It is quite clear, and there are already some questions about this on SO. The second example is not an option, because a standalone control is not validated with the whole form. So I definitely need a name.

The problem is: I don't have anything unique that could be used as a name. The form displays a dynamic collection of entities, and their names are to be entered by the user. I tried to use the element's index inside the collection, but as I add or remove elements, this will also change. Angular seems not to be capable of handling changing form element names, as you can see in this plunker. (Just change the second element, delete the first and add another one - it will produce strange results.)

Is there any way to solve this without validating every form control by hand?

Upvotes: 2

Views: 1226

Answers (1)

user4676340
user4676340

Reputation:

I guess that you use a *ngFor right ?

If so, you can use a custom trackBy function, and name them after the index. This would give

<div *ngfor="let x of y; let i = index; trackBy: myTrackBy" [name]="'myField_' + i">...</div>

In your TS

myTrackBy(index, item) {
  return item.id || index; // try returning the item ID first, otherwise the index
}

Upvotes: 3

Related Questions