Sunday, 3 November 2019

What is Attribute binding in angular?


Attribute Binding: When we are talking about binding, we are binding with DOM properties not the HTML properties. In some cases, for some attributes, DOM does not have corresponding properties. In that case we cannot use string interpolation or property binding. For example, colspan, aria attributes have DOM properties. In this case we can use attribute binding. Use attribute binding only when DOM does not have its property or else, we can use interpolation or property binding.
See the below example









In the above example we have hard coded the colspan value to 2. If we want to pass the value dynamically then

If we use interpolation to bind columnSpan property of the component class to colspan attribute of the <th> element we get the error - Can't bind to 'colspan' since it isn't a known property of 'th'

<th colspan="{{columnSpan}}">

We get the same error if we use Property Binding
<th [colspan]="columnSpan">

So, in this case we can use attribute binding.
<th [attr.colspan]="columnSpan">

The same is true when using interpolation
<th attr.colspan="{{columnSpan}}">











No comments:

Post a Comment