Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need to mention name attribute or ngModelOptions="{standalone: true}" while using ngModel?

I am working on an Angular Form. I have a domain model with some properties. I am binding them by using ngModel.

During this, if I don't use name attribute then I get the below error.

ERROR 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}">

Why do I need to mention name attribute or ngModelOptions while I am binding domain model in two-way binding?

When I applied ngModelOptions="{standalone: true}" to all of my fields, then my form's valid = true in all cases whether the control (with property required) has value or not.

My form is:

<form #detailForm="ngForm" (ngSubmit)="save(detailForm)" id="ngForm">
</form>

While my submit button is outside the form:

<input type="button" form="ngForm" class='Button' value="Save" (click)="detailForm.ngSubmit.emit()" [disabled]="!detailForm.form.valid" />
like image 591
TAB Avatar asked Dec 22 '22 23:12

TAB


2 Answers

Form is just a set of key/value pairs. Name is the key which is used to identify/get/set the value of this control, so you need to specify the name of each control. When you set ngModelOptions="{standalone: true}" you tell angular to not include this input into the form. That's why your form is always valid. It is actually empty.

https://angular.io/api/forms/NgModel#options

like image 135
Dimanoid Avatar answered Dec 28 '22 11:12

Dimanoid


I encounter this problem with a dynamic form. I must add new row into my form (which include inputs) and when I add new data to my form old fields values was clean.

I fix this with:

..*ngFor="let item in formArr; let i = index"...
    ..name="myInput-{{i}}" #myInput{{i}}="ngModel"..
like image 41
Carnaru Valentin Avatar answered Dec 28 '22 09:12

Carnaru Valentin