0
0
Angularframework~5 mins

Property binding with square brackets in Angular

Choose your learning style9 modes available
Introduction

Property binding lets you set HTML element properties from your component data. It keeps your page dynamic and interactive without extra code.

When you want to set an element's attribute like <code>src</code> or <code>disabled</code> based on component data.
When you want to update the UI automatically when your data changes.
When you want to pass values from your component to child components.
When you want to control form inputs or buttons dynamically.
When you want to bind to DOM properties that are not simple HTML attributes.
Syntax
Angular
<element [property]="componentValue"></element>
Use square brackets [] around the property name to bind it to a component variable or expression.
Angular updates the property automatically when the component value changes.
Examples
Sets the src property of the image to the imageUrl variable from the component.
Angular
<img [src]="imageUrl">
Disables the button if isDisabled is true in the component.
Angular
<button [disabled]="isDisabled">Click me</button>
Sets the input box value to the userName from the component.
Angular
<input [value]="userName">
Sample Program

This component shows a greeting with the user name. The input box uses property binding to set its value from userName. When you type, it updates userName. The submit button is disabled if userName is empty.

It uses property binding with square brackets to keep the input and button properties in sync with the component data.

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

@Component({
  selector: 'app-root',
  template: `
    <h1>Welcome, {{ userName }}!</h1>
    <input [value]="userName" (input)="userName = $event.target.value" aria-label="User name input">
    <button [disabled]="!userName">Submit</button>
  `
})
export class AppComponent {
  userName = 'Alice';
}
OutputSuccess
Important Notes

Property binding updates the DOM property, not the HTML attribute. This is important for elements like input where the property controls the displayed value.

Always use property binding for dynamic values instead of string interpolation inside attributes to avoid unexpected behavior.

Use aria-label or other accessibility attributes to keep your UI accessible.

Summary

Property binding with square brackets connects component data to element properties.

It keeps the UI updated automatically when data changes.

Use it for dynamic attributes like src, disabled, and value.