Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between [(ngModel)] and [ngModel] for binding state to property?

Here is a template example:

<input type="number" class="form-control" [(ngModel)]="overRideRate" formControlName="OverRideRate">  <input type="number" class="form-control" [ngModel]="overRideRate" formControlName="OverRideRate"> 

Here both of them do the same thing. Which one is preferred and why?

like image 782
LittleDragon Avatar asked Feb 28 '17 09:02

LittleDragon


People also ask

What is the difference between [( ngModel )] and ngModel?

What is the difference between (ngModel) and [(ngModel)] ? I know you're in a hurry for the answer, but a bit of understanding helps. The answer is: (ngModel) causes a 1-way data-binding, whereas [(ngModel)] ensures a two-way data binding.

What is [( ngModel )] used for?

The ng-model directive binds the value of HTML controls (input, select, text-area) to application data. It is a part of the FormsModule. This directive is used by itself or as part of a larger form. It accepts a domain model as an optional Input.

What does [( ngModel )] mean in Angular?

ngModel is a directive which binds input, select and textarea, and stores the required user value in a variable and we can use that variable whenever we require that value. It also is used during validations in a form. We can use ngModel with: input.

Is ngModel property binding?

NgModel is a directive that creates the FormControl instance from a domain model and binds it to a form control element. It uses two kinds of binding: Property binding.


2 Answers

[(ngModel)]="overRideRate" is the short form of [ngModel]="overRideRate" (ngModelChange)="overRideRate = $event"

  • [ngModel]="overRideRate" is to bind overRideRate to the input.value
  • (ngModelChange)="overRideRate = $event" is to update overRideRate with the value of input.value when the change event was emitted.

Together they are what Angular2 provides for two-way binding.

like image 164
Günter Zöchbauer Avatar answered Nov 15 '22 14:11

Günter Zöchbauer


[ngModel]="currentHero.name" is the syntax for one-way binding, while,

[(ngModel)]="currentHero.name" is for two-way binding, and the syntax is compound from:

[ngModel]="currentHero.name" and (ngModelChange)="currentHero.name = $event"

If you only need to pass model, use the first one. If your model needs to listen change events (e.g. when input field value changes), use the second one.

like image 33
seidme Avatar answered Nov 15 '22 13:11

seidme