Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Data Binding in Angular

Data binding is a core concept in Angular that allows you to synchronize data between the component class and the template. This tutorial provides an overview of the different types of data binding in Angular, including examples and best practices.

Types of Data Binding in Angular

Angular provides several types of data binding:

  • Interpolation: Binds a property from the component to the template using curly braces.
  • Property Binding: Binds a property to an element's attribute using square brackets.
  • Event Binding: Binds an event to a method in the component using parentheses.
  • Two-Way Binding: Combines property and event binding using the ngModel directive.

Interpolation

Interpolation allows you to bind a component property to the template using curly braces:

// Component class
import { Component } from '@angular/core';

@Component({
  selector: 'app-interpolation',
  template: '<p>{{ message }}</p>'
})
export class InterpolationComponent {
  message: string = 'Hello, Angular!';
}

The template will display the value of the message property.

Property Binding

Property binding allows you to bind a property to an element's attribute using square brackets:

// Component class
import { Component } from '@angular/core';

@Component({
  selector: 'app-property-binding',
  template: '<img [src]="imageUrl" alt="Angular Logo">'
})
export class PropertyBindingComponent {
  imageUrl: string = 'assets/angular-logo.png';
}

The src attribute of the <img> element is bound to the imageUrl property.

Event Binding

Event binding allows you to bind an event to a method in the component using parentheses:

// Component class
import { Component } from '@angular/core';

@Component({
  selector: 'app-event-binding',
  template: '<button (click)="handleClick()">Click me!</button>'
})
export class EventBindingComponent {
  handleClick() {
    alert('Button clicked!');
  }
}

When the button is clicked, the handleClick method is called.

Two-Way Binding

Two-way binding allows you to synchronize data between the component class and the template using the ngModel directive:

// Component class
import { Component } from '@angular/core';

@Component({
  selector: 'app-two-way-binding',
  template: '<input [(ngModel)]="name"><p>Hello, {{ name }}!</p>'
})
export class TwoWayBindingComponent {
  name: string = '';
}

Changes to the input field update the name property, and changes to the name property update the input field.

Conclusion

Data binding is a powerful feature in Angular that allows you to synchronize data between the component class and the template. By understanding and using interpolation, property binding, event binding, and two-way binding, you can build dynamic and interactive Angular applications. Happy coding!