What is property binding in Angular?

Key takeaways:

  • Property binding allows us to bind the values of component properties to HTML element properties, enabling dynamic updates to the view based on the component's state.

  • It is one-way data binding from the component to the view.

  • It uses square brackets [] around the target property to connect the HTML element’s property with a variable or expression in the component.

  • Property binding has many types including element property binding, component property binding, directive property binding, attribute property binding, etc.

  • Properly using the different types of property binding ensures better control over your application's UI and performance.

Property binding is a fundamental feature in Angular that enables developers to set values for properties of HTML elements or directives. In property binding, data gets passed from the component class to the view using one-way data binding. It involves binding the property of an HTML element to a variable defined in the component class. It helps in updating the view based on the component’s state, making the applications more dynamic and responsive.

Syntax

The syntax for property binding uses square brackets [] to enclose the target property. Here are some examples:

// Basic property binding
<img [src]="imageUrl">
// Binding to a DOM property
<div [hidden]="isHidden">Content</div>
// Binding to a custom property
<app-child [message]="parentMessage"></app-child>
Examples of property binding in Angular

Types of property binding

Let’s go through some types of property binding.

Element property binding

Element property binding allows us to set values for DOM element properties directly. This is the most basic form of property binding.

<element [propertyName]="expression">
An example of element property binding

Component property binding

Component property binding is used to pass data from a parent component to a child component through the child’s input properties.

<child-component [childProperty]="parentProperty">
An example of component property binding

Directive property binding

Directive property binding is used to pass values to directive inputs, allowing us to modify directive behavior dynamically.

Built-in directive

Angular provides several built-in directives that we can use right out of the box. These are categorized into three types:

  1. Component directives: Components are directives with templates. They use the @Component decorator.

  2. Structural directives: These directives change the DOM layout by adding and removing elements.

  3. Attribute directive: These directives change the appearance or behavior of an element.

Custom directive

Custom directives allow us to create reusable behaviors specific to our application.

Attribute property binding

Attribute property binding is used when we need to set HTML attributes that don’t have corresponding DOM properties.

<element [attr.attributeName]="expression">
An example of attribute property binding

Example of using property binding in Angular

In this example, we’ll demonstrate how to toggle between two images using property binding and event handling in Angular. We’ll modify the component class (app.component.ts) and its corresponding HTML template (app.component.html) to achieve this behavior.

import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
title = 'prop-binding';
isShowImage = false;
educativeLogo =
'https://res.cloudinary.com/dz4tt9omp/image/upload/v1671977557/educate.png';
angularLogo =
'https://res.cloudinary.com/dz4tt9omp/image/upload/v1671977926/angula.png';
imageToggler() {
this.isShowImage = !this.isShowImage;
}
}

In the above code:

  • Line 10: We’ll create a variable called isShowImage and set its value to false. The isShowImage helps us to determine the toggle state of the images.
  • Line 11: We’ll create a variable called educativeLogo, which holds the first image.
  • Line 13: We create a variable called angularLogo that holds the second image.
  • Line 16: We create a function called imageToggler(). Inside this function, we create a toggle effect by setting the isShowImage variable to false using the logical not(!) operator creating a boolean effect. The imageToggler() function can now set the isShowImage variable to either true or false using a click event.

We can proceed to the template file and integrate the variables that we’ve created inside our HTML file.

<div class="mt-5 container d-flex align-items-center justify-content-center">
<div class="card" style="width: 18rem;">
<img [src]="isShowImage ? educativeLogo : angularLogo" class="card-img-top" alt="image toggle">
<div class="card-body">
<button style="margin-left: 66px" (click)="imageToggler()" class="btn btn-primary">Toggle Image</button>
</div>
</div>
</div>

In the above code:

  • Line 4: We use property binding to wrap around the src attribute using the square brackets. We then conditionally render the images based on the state of the isShowImage variable defined in our component class using a ternary operator. If the isShowImage is true, the educativeLogo image gets displayed, while if the isShowImage is false, the angularLogo gets displayed.
  • Line 6: We use the (click) event handler in Angular to call the imageToggler() function.

Application demo

Let’s run the application below:

{
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=827846
  "recommendations": ["angular.ng-template"]
}
Image toggle application in Angular

Once the code widget above gets compiled, we can see the image toggle application in action.

Best practices

Here are some tips for using property binding in Angular:

  1. Use appropriate syntax: Choose between interpolation and property binding based on the use case.

  2. Avoid complex expressions: Keep binding expressions simple and move complex logic to components.

  3. Performance considerations: Use pure pipes and implement change detection strategies.

  4. Type safety: Utilize TypeScript’s type-checking capabilities.

  5. Error handling: Implement proper error handling for bound properties.

Conclusion

Property binding is a powerful feature in Angular that enables dynamic web applications by allowing components to control element properties. Understanding the different types of binding and when to use each one is crucial for building efficient and maintainable Angular applications. By following best practices and understanding the differences between property binding and other binding types, we can create more robust and performant applications.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


What is attribute and property binding?

  • Attribute binding: Sets HTML attributes using [attr.attributeName] syntax. Attributes are defined by HTML.

  • Property binding: Sets DOM properties using [propertyName] syntax. Properties are defined by the DOM.

// Attribute binding
<td [attr.colspan]="columnSpan">Content</td>

// Property binding
<img [src]="imageUrl">

What's the difference between interpolation and property binding?

Syntax:

  • Interpolation uses double curly braces: {{ expression }}
  • Property binding uses square brackets: [property]="expression"

Usage:

  • Interpolation is best for string values and simple expressions.
  • Property binding is preferred for non-string properties and complex expressions.

Direction:

  • Both are one-way bindings from component to view.
  • Property binding offers more explicit control over the binding.

What is the difference between property binding and event binding in Angular?

Direction:

  • Property binding: Component to view (one-way)
  • Event binding: View to component (one-way)

Syntax:

  • Property binding: [property]="expression"
  • Event binding: (event)="handler()"

Purpose:

  • Property binding: Sets element properties
  • Event binding: Handles user actions and events

Free Resources