Angular2+ data flow:
In Angular the data can flow between the model (component class ts.file) and view (html of the component) in the following manners:
- From the model to the view.
- From the view to the model.
- Data flows in both directions, also known as 2 way data binding.
Syntax:
model to view:
<input type="text" [ngModel]="overRideRate">
This syntax is also known as property binding. Now if the overRideRate
property of the input field changes the view automatically will get updated. However if the view updates when the user enters a number the overRideRate
property will not be updated.
view to model:
(input)="change($event)" // calling a method called change from the component class
(input)="overRideRate=$event.target.value" // on input save the new value in the title property
What happens here is that an event is triggered (in this case input event, but could be any event). We then can call methods of the component class or directly save the property in a class property.
2-way data binding:
<input [(ngModel)]="overRideRate" type="text" >
The following syntax is used for 2-way data binding. It is basically a syntactic sugar for both:
- Binding model to view.
- Binding view to model
Now something changes inside our class this will reflect our view (model to view), and whenever the user changes the input the model will be updated (view to model).
[ngModel]
- it's property binding only, not two-way binding. So entering new value will not updateoverRideRate
. – Pantheism[(ngModel)]
, Two-way Data Binding in Angular – Bobinette<input [value]="username" ...>
. When following it for<textarea [value]="username">
, found it works for"@angular/core": "^7.2.16"
. After upgrading to"@angular/core": "^9.1.3"
it breaks.username
isn't populated back totextarea
anymore. Tried[attr.value]="username"
, no luck too. Have to use[ngModel]="username"
to make it work which works for"@angular/core": "^7.2.16"
of course. – Bobinette"@angular/core": "^9.1.4"
.<textarea [value]="username">
still works fine. Turned out that something else prevents it from working in ourAngular 9.1.3
project mentioned previously. – Bobinette