Telerik blogs
AngularT2_Light_1200x303

Data binding can be confusing when you’re getting started in Angular. Let’s break it down! This post covers one-way attribute binding.

This is another post on data binding in Angular. If you have not, make sure to check out the previous posts where we have looked at interpolation, event binding and property binding.

Prerequisites

This post is suited for all levels of frontend developers who use Angular, so being conversant with beginner concepts and installation processes is not assumed.

Here are a few prerequisites you should have to follow this article’s demonstration with Angular 12:

  • Visual Studio Code as your integrated development environment
  • Node version 11.0 installed on your machine
  • Node Package Manager version 6.7 (it usually ships with Node installation).
  • Angular CLI version 8.0 or above
  • The latest version of Angular (version 12)
// run the command in a terminal
ng version

Confirm that you are using version 12, and update to 12 if you are not.

Other nice-to-haves include:

  • Working knowledge of the Angular framework at a beginner level

What We Are Building

We are going to use the Kendo UI Template Wizard to generate a new test project inside which we will demonstrate how attribute binding works.

Open up your VS Code application and go to the Command Palette (type Command + Shift + P on Mac or Ctrl + Shift + P on PC) to open the Kendo UI Wizard. If you do not have it installed already, then go to the Extensions tab, search for Kendo UI Template Wizard and install it. Restart the VS Code app and then go back to the Command Palette to open the Kendo UI Wizard.

Kendo UI Template Wizard has fields for Project Name and Output Path

Choose a project name and a location on your machine where you want it to be saved, and click “Next.”

Choose Angular and then choose blank with 1 page and click “Next.”

Wizard shows page types and number of pages

Choose default CSS as your style choice and click “Create.” Once it finishes, click on "Open new project.” Open the terminal and download all the Node dependencies with this command:

npm install

After that, you can run the application on the dev server with this command:

ng serve

The application should look like this if you visit localhost:4200 in your browser.

Welcome to Kendo UI for Angular. Focus on the core of your application and spend less time sweating over the UI. Get Started.

Now we are all set. This is how the syntax of attribute binding looks:

[attr.attributeName]="expression"

What Is Attribute Binding?

Attribute binding basically allows you to bind attributes of elements from the component to the view template. It is a one-way data binding approach just like property binding.

Attribute binding in Angular helps you set values for attributes directly. With attribute binding, you can improve accessibility.  —  Angular Docs

If you have followed the series, you might ask what the difference is between property binding and attribute binding. One way to look at it is the difference between attributes and properties.

Attributes vs. Properties

Attributes and properties are not really the same because attributes are defined by HTML and properties are defined by the DOM itself. Furthermore, attributes basically initialize DOM properties, and, once they do, the values of those properties cannot change. Meanwhile, property values can change.

A more direct way to see them is HTML attributes and DOM properties. We can see an illustration that better explains this:

In your app component.html file, replace the content with the code block below:

<div class="content">
    <app-header></app-header>
    <router-outlet>
        <input type="text" value="New value"> <br>
    </router-outlet>
    
</div>
<div class="footer">
    <app-footer></app-footer>
</div>

Now run the dev server command below to get the app running in localhost:

ng serve

You can see the input field here with the value of “new value” as expected.

Kendo UI for Angular and a box that says New Value

Now click on the input box and inspect it to pull up your browser console. Inside it, type out these commands:

$0.getAttribute(‘value’)
$0.value

You will see they both return the same value. Now change the text in the input box to something else and re-run the two command above in the console. The results show that attributes do not change.

$0.getAttribute(‘value’) and $0.value both show  “New value”. Then $0.getAttribute(‘value’) stays the same but $0.value changes to just  “New”.

Why Attribute Binding?

Angular recommends using property binding to achieve one-way data binding in our applications. Since we know that attribute binding and property binding are similar, here is the difference and why you might need to use attribute binding over property binding. Besides the syntax, some attributes are not supported by DOM elements natively. Yes, I know you saw the value attribute and the value property, but this is indeed a possible occurrence. Angular solves for that by letting you do attribute binding.

The Colspan Example

Column span is a table attribute you use to define the span of a table element. Replace the content in the app.component.html file with the code block below:

<div class="content">
    <app-header></app-header>
    <router-outlet>
        <input type="text" value="New value"> <br> <br>
<table  style="border-collapse: collapse;">
            <thead  style="border: 1px solid black;">
                <tr>
                    <th colspan="1"  style="border: 1px solid black;">
                        Friends List
                    </th>
                </tr>
            </thead>
            <tbody  style="border: 1px solid black;">
                <tr>
                    <td>Lotanna</td>
                    <td>Nwose</td>
                </tr>
                <tr>
                    <td>John</td>
                    <td>Doe</td>
                </tr>
                <tr>
                    <td>Olivia</td>
                    <td>Pope</td>
                </tr>
                <tr>
                    <td>Jeff</td>
                    <td>Bezos</td>
                </tr>
            </tbody>
        </table>
    </router-outlet>
    
</div>
<div class="footer">
    <app-footer></app-footer>
</div>

This is a simple table with 4 rows and 2 columns. We are going define column span for the table header.

Friends List header is in a shorter box than the names below it

Now make sure your app component.ts file looks like this:

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
colVal: number = 2
}

We initialized the value 2 for it. Now if you go back to the template and change the 1 to colVal, you see nothing happens. If you make it an interpolation case too, again nothing happens. If you try to do property binding, you will get the unknown property error saying it is not a known property of the table element.

The only way this can be bound is through Angular’s attribute binding. Go ahead and change the block below to include the attribute syntax like this:

<tr>
    <th [attr.colspan]="colVal"  style="border: 1px solid black;">
                        Friends List
     </th>
</tr>

You see that the column spacing works now as you expect it to.

Conclusion

In this post we looked into attribute binding, how it is used and when it is used. We looked at how similar it is to the property binding and the recommendations from Angular. We also saw why attribute binding can be important with colspan. Stay tuned for more posts on data binding.


5E9A474B-EBDB-439E-8A4A-3B041B0BEDA6
About the Author

Nwose Lotanna Victor

Nwose Lotanna Victor is a web technology enthusiast who documents his learning process with technical articles and tutorials. He is a freelance frontend web developer based in Lagos, Nigeria. Passionate about inclusion, community-building and movies in Africa, he enjoys learning new things and traveling.

Related Posts

Comments

Comments are disabled in preview mode.