Angular Tutorial
Templates & Data Binding
In Angular, we have a TypeScript class representing logical state, and an HTML Template representing the View.Data Binding is the magical bridge that passes data seamlessly between the Class and the HTML Template. Angular provides four main types of Data Binding.
1. String Interpolation ({{ value }})
Interpolation is the easiest way to display a variable from your TypeScript class directly onto the screen as text. You wrap the variable in double curly braces.
// .ts class
userName: string = "Alice";
// .html template
<h1>Welcome back, {{ userName }}!</h1>Anytime userName changes in the class, Angular will instantly update the DOM with the new value automatically.
2. Property Binding ([property])
If you want to bind data to an HTML Attribute (like an image src, a button's disabled state, or a link's href), you use Property Binding with square brackets.
// .ts class
logoUrl: string = "https://example.com/logo.png";
isButtonDisabled: boolean = true;
// .html template
<img [src]="logoUrl" alt="Logo">
<button [disabled]="isButtonDisabled">Submit</button>3. Event Binding ((event))
When a user interacts with the UI (like clicking a button or typing in a box), you need to send that action back to your TypeScript class to execute logic. You use parentheses for Event Binding.
// .ts class
saveData() {
console.log("Data saved safely!");
}
// .html template
<button (click)="saveData()">Save Changes</button>You can bind to standard DOM events like (keyup), (mouseenter), and even custom Component Event Emitters.
4. Two-Way Binding ([(ngModel)])
What if you have an input field where you want to instantly update a variable as the user types, AND you want the input box to instantly change if you modify the variable in TypeScript? This requires Two-Way binding, famously known as "Banana in a Box" syntax: [(...)].
// To use this, you must import FormsModule in your app config!
// .ts class
searchQuery: string = "initial text";
// .html template
<input type="text" [(ngModel)]="searchQuery">
<p>You are typing: {{ searchQuery }}</p>As you type inside the input, the text below dynamically updates simultaneously. If somehow the code changes `searchQuery`, the input text field updates as well.
Conclusion
Data Binding allows your HTML Views and TypeScript logic to maintain a cohesive, perfectly synchronized state. Next, let's learn how to radically alter the DOM structurally using structural Directives (ngIf and ngFor).