Property Binding in Angular Explained

Property Binding in Angular Explained

Property binding is connecting a variable from component to view.

It lets you set a property of an element in the view to property in the component.

You can use it to set the properties of existing and custom components or directives (properties decorated with @Input

Property Binding Syntax

We bind properties such as **class**, **href**, **src**, **textContent**, etc to a source.

The general syntax would be like this.

[binding-target]=”binding-source”

The binding-target (or target property) is enclosed in a square bracket []. It should match the name of the property of the enclosing element.

Lets do an example with and

app.component.ts

app.component.html

Output of Code

Points to note about Property Binding

1. Property Binding is one way

Property binding is one way as values go from the component to the template.

2. Return the proper type

The binding expression should return the correct type. The type that the target property expects. Else it won't work.

3. Should not change the state of the app

There are several element property names in the camel case, while their corresponding attributes are not. For example rowSpan & colSpan properties of the table are in the camel case. The HTML attributes are all lowercase (rowspan & colspan).

4. Always Remember the brackets

The brackets, **[]**, tell Angular to evaluate the template expression. If you omit the brackets, Angular treats the expression as a constant string and initializes the target property with the string.

Property Binding Vs Interpolation

Everything that can be done from interpolation can also be done using the Property binding.

Interpolation is actually a shorthand for binding to the **textContent** property of an element.

Interpolation is simple and readable. Interpolation requires the expression to return a string. If you want to set an element property to a non-string data value, you must use property binding.

Thank you for reading this post, I hope you enjoyed and learn something new today. Feel free to contact me through my blog if you have questions, I will be more than happy to help.

LinkedIn: linkedin.com/in/zainuleb

Github: github.com/zainuleb (Github)

Email:

Stay safe and Happy learning!