This chapter provides a thorough discussion of the fundamental concepts of data binding in Angular 12. By the end of this chapter, you will understand the various types of data binding, the event types associated with data binding, and what each type does.
The Types of Data Binding in Angular
In Angular 12, there are four types of data binding.
Event Binding
String Interpolation
Property Binding
Two way Data Binding
Event Binding
Event binding is used to handle user-generated events such as hovering over objects, mouse clicks, keystrokes, and so on.
In angular 12 you should define the target event within the parenthesis. The diagram below shows various event binding event types
(click) ="functionName()" (dblclick) ="functionName()" (submit) ="functionName()" (blur) ="functionName()" (focus) ="functionName()" (scroll) ="functionName()" (cut) ="functionName()" (copy) ="functionName()" (paste) ="functionName()" (keyup) ="functionName()" (keypress) ="functionName()" (keydown) ="functionName()" (mouseup) ="functionName()" (mousedown) ="functionName()" (mousedown) ="functionName()" (drag) ="functionName()" (drop) ="functionName()" (dragover) ="functionName()" |
Angular 12 Event binding Example
<button (click)="functionName()">Click</button> Markup export class AppComponent{ functionName(){ alert("Hello World"); } } |
String Interpolation
The string interpolation allows the angular template to retrieve data from the typescript template. This makes it simple to dynamically display data on the HTML template view.
An Example of String Interpolation
import { Component} from "@angular/core"; @Component({ selector: "ng-app", template: " <h3>{{Hello world}} </h3>" }) export class NgComponent{ amazon: string = "sample"; } |
Property Binding
This type of data binding, as the name implies, entails assigning values to HTML properties and directives such as adding button toggle, sharing component values, and so on.
An example of Property Binding
import { Component} from "@angular/core"; @Component({ selector: "ng-app", template: " <img [src]="itemUrl"> }) export class NgComponent{ amazon: string = "../assets/boy.jpg"; } |
Two way Data Binding
Finally, the two way data binding entails sharing of data between the component class and the angular template. By the term two way, it means that if a value of a given place is changed then the value of the defined property is updated. The following is an example of a two way data binding.
Example of a two way data binding
import { Component} from "@angular/core"; @Component({ selector: "ng-app", template: " <input type='text' [(ngModel)]= 'name'> <br/> {{name}} "}) export class NgComponent{ name: string = "hello world"; } |
Conclusion
We have discussed various types of data bindings and their applications using well-illustrated examples. The following chapter will teach us about the Angular 12 - Directives