Header add

In this article we will discuss Angular Attribute Binding. In our previous articles we discussed Interpolation and  Property binding that deal with binding Component class properties to HTML element properties and not Attributes.

However, in some situations we want to be able to bind to HTML element attributes. For example, colspan and aria attributes does not have corresponding DOM properties. So in this case we want to be able to bind to HTML element attributes.

To make  this happen, Angular provides attribute binding. With attribute binding we can set the value of an attribute directly. Angular team recommends to use Property binding when possible and use attribute binding only when there is no corresponding element property to bind.

Let us understand Attribute Binding in Angular with an example. We want to display Employee Details in a table as shown below.

Let's discuss how to we achieve this. We take a separate employee Component and do the stuff.

 Open the employee.component.css and add the below css to design the table

Open the employee.component.ts and modify the employee.component.ts file as shown below. Here within the component decorator, we are providing the stylesUrl and templateUrl values to the external files. Then as part of the Component class, we are creating the required employee properties.

Open the employee.component.html and add the html like below; we added div with bootstrap for styling only.

➥ Using Angular Interpolation

If you notice, here we have hardcode the colspan value to 2 in the HTML file i.e. in the employee.component.html file. Let us say we also want to bind this (colspan) value from a property of the component class. As you see we alredy added a dynamic property of colspan in component file

➥ Modify the empolyee.component.html file

When you run the application you can get the below error.

So it clear that you cannot use angular interpolation to bind the colspan attribute of th element.

➥ Let's do try using Property Binding

When you run the application and will same error is throwing.

➥ Using Attribute Binding

To tell the angular framework that we are setting an attribute value, we have to prefix the attribute name with the attr and a DOT as shown below.

This is working file for us.

When you run the application you can see the output like below;

Also we can do this using angular interpolation just using 'attr' keyword like below;

You can also error-free output using this.

The Angular team recommends using the property binding or Interpolation whenever possible and use the attribute binding only when there is no corresponding element property to bind. 

In this tutorial we discussed Angular Attribute Binding. If have any question related to this topic then give your feedback.

You May Also Like...

Post a Comment

Previous Post Next Post