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?
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.
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.
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.
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.
[(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.
[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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With