☰ See All Chapters |
Angular Data Binding
Angular Components are useless if they do not show any dynamic data. They also need to respond to user interactions and react to events. Data binding is a process where data is passed between Angular Component and view (Template).
Template Expression
Before diving into the Data Binding in Angular, let us look at the Template Expression. In our previous examples and as well as in above image, we used {{title} expression to display the value of the title property from the component class.
The content inside the double braces is called Template Expression in Angular.
The Angular first evaluates the Template Expression and converts it into a string. This template expression should be written in such a way that, finally it should evaluate to string.
Template expressions can contain more than just property names. They can hold constant values (numbers and strings) and the results of simple JavaScript operations. For example, {{3*6+2}} will be displayed as 20 and {{'Angular'+'JS'}} will be displayed as AngularJS.
An expression can operate on class properties, so if you want to concatenate firstVal and secondVal, the expression is {{firstVal+secondVal}}. Similarly, if num equals 5, the expression {{num+'0'}} will be displayed as 50.
Similar expressions can be inserted in the template wherever strings are appropriate. For example, the class attribute of a <button> could be set to {{ buttonClass }} and the id of a <div> could be set to {{ divId }}.
An expression can be used to execute JavaScript functions. If returnTwo() always returns a value of 2, the {{ returnTwo() }} expression will evaluate to 2.
Types of data binding
All Chapters