Welcome back! In this installment, we’ll explore Data Binding – Angular’s powerful mechanism for synchronizing your application data with the user interface. This is where Angular truly shines!
Understanding Data Binding
Data binding creates a connection between:
- Your component class (TypeScript)
- Your template (HTML)
Angular offers four types of data binding:
Binding Type | Syntax | Direction |
---|---|---|
Interpolation | {{ expression }} | Component → View |
Property Binding | [property]="expr" | Component → View |
Event Binding | (event)="handler" | View → Component |
Two-Way Binding | [(ngModel)]="prop" | Component ↔ View |
1. Interpolation (Displaying Values)
The simplest form – displays component properties in the view:
// component.ts title = 'Data Binding Demo'; currentDate = new Date();
<!-- template.html --> <h1>{{ title }}</h1> <p>Today is {{ currentDate | date }}</p> <p>2 + 2 = {{ 2 + 2 }}</p>
💡 Note: You can use pipes (
|
) to format output
2. Property Binding (Setting Element Properties)
Bind component properties to HTML element properties:
// component.ts imageUrl = 'assets/logo.png'; isDisabled = true;
<!-- template.html --> <img [src]="imageUrl" [alt]="title"> <button [disabled]="isDisabled">Click me</button>
3. Event Binding (Responding to User Actions)
Execute component methods when events occur:
// component.ts count = 0; increment() { this.count++; }
<!-- template.html --> <p>Count: {{ count }}</p> <button (click)="increment()">Add +1</button>
4. Two-Way Binding with ngModel
Keeps component properties and form inputs in sync:
- First, import
FormsModule
in your app module:
// app.module.ts import { FormsModule } from '@angular/forms'; @NgModule({ imports: [FormsModule] })
- Use in your component:
// component.ts username = '';
<!-- template.html --> <input [(ngModel)]="username" placeholder="Enter your name"> <p>Hello, {{ username }}!</p>
Comparing the Binding Types
<!-- Interpolation --> <p>{{ message }}</p> <!-- Property Binding --> <p [textContent]="message"></p> <!-- Event Binding --> <button (click)="showAlert()">Click</button> <!-- Two-Way Binding --> <input [(ngModel)]="email">
Practical Example: User Profile Form
Let’s build a complete example:
// profile.component.ts export class ProfileComponent { user = { name: '', email: '', newsletter: false }; submit() { console.log('Form submitted:', this.user); } }
html
<!-- profile.component.html --> <form (ngSubmit)="submit()"> <div> <label>Name:</label> <input [(ngModel)]="user.name" name="name" required> </div> <div> <label>Email:</label> <input [(ngModel)]="user.email" name="email" type="email" required> </div> <div> <label> <input [(ngModel)]="user.newsletter" name="newsletter" type="checkbox"> Subscribe to newsletter </label> </div> <button type="submit">Save</button> </form> <div *ngIf="user.name"> <h3>Preview:</h3> <p>Name: {{ user.name }}</p> <p>Email: {{ user.email }}</p> <p>Newsletter: {{ user.newsletter ? 'Yes' : 'No' }}</p> </div>
Best Practices
- Avoid complex expressions in templates – move logic to components
- Use proper typing for better maintainability
- Consider change detection impact with frequent updates
- Prefer one-way binding when possible for better predictability
Common Pitfalls
❌ Forgetting to import FormsModule
for ngModel
❌ Using interpolation when property binding is needed
❌ Overusing two-way binding when one-way would suffice
Hands-On Exercise
Create a temperature converter component with:
- Two input fields (Celsius and Fahrenheit)
- Real-time conversion between them
- Use proper binding for each direction
- Style the inputs differently when values are invalid (< -273.15°C)
What’s Next?
In Part 5, we’ll dive into Directives in Angular – powerful tools to extend HTML with custom behavior!