Angular Property Binding

wordpress featured image

Angular Property Binding helps with setting values for properties of HTML elements. Property binding can also be used for managing feature states of the elements, and also sharing values between components.

How data flows

With Property Binding, values move in one direction, from parent to the child component.
This is also known as attribute binding.

How to bind a property

To bind a property, it is required to be enclosed in square brackets.
For example, if you want to set the value for an image source directly,

// image-viewer.component.ts
@Component({
  ...
  templateUrl: './image-viewer.component.html'
})
export class ImageViewerComponent {
  dynamicImageURL: string = 'https://some-url-path.jpg';

  changeURL() {{
    this.dynamicImageURL = 'https://some-other-url-for-image.png';
  }
}

// image-viewer.component.html
<img [src]="dynamicImageURL">
<button (click)="changeURL()">Change Image</button>

In the above example, [src]=”dynamicImageURL” is known as property binding.

If the above code is executed, the image-viewer.component would display the 1st image.

If the ‘Change Image’ button is clicked afterwards, then the image would change to the second image.

This is due to Angular property binding.

Using in Custom Components

Lets consider we have a child component.

// user.interface.ts
export interface IUser {
  name: string;
  age: number;
}

// child.component.ts
@Component({
  selector: 'app-child',
  template: `
    Hi {{ userDetails?.name }},
    Your age is {{ userDetails?.age }} years
  `
})
export class ChildComponent {
  @Input() userDetails: IUser;
}

and the parent component

// parent.component.ts
@Component({
  selector: 'app-parent',
  template: `<app-child [userDetails]="myUser"></app-child>`
})
export class ParentComponent {
  myUser: IUser = { name: 'Nayak', age: 100 };
}

In the above example you can see parent-to-child communication using Property binding.

Additional ways

It is also possible to bind string values directly, without using the square bracket notation. Without the [ ] notation, angular will treat the values as string literals and then use the static value to bind to the property.

<app-child name="Murari Nayak"></app-child>

Read more on data binding best practices here. And more on Angular here.

Leave a Reply