Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Property Bindings in Angular 2

DZone's Guide to

Property Bindings in Angular 2

The primary way to bind data in Angular 2 is through property bindings. This allows you to bind values to properties of an element to modify their behavior or appearance. In this article, we’ll look at the different ways property bindings are used to pull data into the view.

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

The primary way to bind data in Angular 2 is through property bindings. This allows you to bind values to properties of an element to modify their behavior or appearance. This can include properties such as class, disabled, href, or textContent. For example, you might load a record from the database that contains a URL to an image, and you can bind that URL into an img element to display that image. In this article, we’ll look at the different ways property bindings are used to pull data into the view.

The syntax for property bindings is to put the property onto the element wrapped in brackets [property]. The name should match the property, usually in a camel case like textContent. We can rewrite the interpolation version (interpolation has double curly braces to bind data inline like {{getName()}}) to use property bindings to look like the following to see several in action.

<div style="float: left; width: 160px">
  <img [src]="user.img">
</div>
<div style="float: left">
  <h2 [textContent]="'User: ' + getName()"></h2>
  <p>GitHub Profile: <a [href]="'https://github.com/' + user.github" [textContent]="user.github"></a></p>
</div>

In figure 1, you can see how property bindings evaluate to the end value. In this example, the controller has a property called "github" that contains a string value. By using the [href]="'https://github.com/' + github" binding, the href property is set based on the result of concatenating https://github.com/ and the value of the controller github property. The textContent property evaluates to the value of the controller property as well.

Property binding flow

Figure 1 – Property binding by evaluating expressions and setting result to element properties.

Like with interpolation, the bindings are evaluated in the component context so it will reference members of the controller. Here you’ve got the [src]="user.img" property binding, which does the same thing as src="{{user.img}}". Both will evaluate the expression to bind the value to the image src property, but the syntax is different. Property bindings do not use the curly braces, and thus, evaluate everything inside of the quotes as the expression.

If you look at [textContent]="'User: ' + getName()" you are setting the content of the element. This is not often used since most developers will find the interpolation version (User {{getName()}}, not shown in the example) to be more readable and concise. However, here the expression is explicitly concatenating the string "User: " with the result of the getName() method. This might give you a new appreciation for how interpolation works, as, under the hood, interpolation will essentially evaluate its own binding this way.

Using the [] syntax binds to an element’s property, not the attribute. This is an important distinction, as properties are the DOM element’s property. This makes it possible to use any valid HTML element property (such as the img src property). So, instead of binding the data to the attribute, you are binding data directly to the DOM element, and this is quite efficient.

These bindings are one way, meaning that the values are set only by changes in the controller and never updated based on changes to the DOM. Using this approach also is helpful to make binding very fast and memory efficient.

Class and Style Property Bindings

There are a couple of special property bindings for setting a class and style property for an element. They are both different from many properties that you typically bind to because they are actually objects that contain a list of classes or styles, and Angular has a special syntax for setting those properties.

The class property on an element is actually a DOMTokenList, which is like a fancy array. You can actually use [class]="getClass()" and it will set a string of class or classes, but this will mess with any of the classes on the element if they are already set. Often you will want to toggle a single class, which you can do by using a [class.className] syntax in the property. It will see the class. prefix for the property binding, and know you are actually binding just a particular class called className. Let’s see an example and how it is rendered.

<!-- isAccent() returns true or false in order to set accent class -->
<h1 class="leading" [class.accent]="isAccent()">Title</h1>
<!-- Renders to the following -->
<h1 class="leading accent">Title</h1>

The class binding syntax is useful for targeting specific classes to be added or removed from an element. It also adds only to the existing classes instead of replacing them entirely, like if you use [class]="getClass()".

Likewise, the style property is actually a CSSStyleDeclaration object, which is a special object that holds all of the CSS properties. Angular has the same type of syntax for style binding to set individual style properties. Using [style.styleName] you can set the value of any valid CSS style. Now, for an example.

<!-- getColor() returns a valid color -->
<h1 [style.color]="getColor()">Title</h1>
<h1 [style.line-height.em]="'2'">Title</h1>
<!-- Renders to the following -->
<h1 style="color: blue;">Title</h1>
<h1 style="line-height: 2em;">Title</h1>

Any valid CSS property can be used here, and it will render the binding as a style value directly on the element. Did you notice the second example has a third item, .em? For properties that accept units, you can use this syntax to declare the unit for the value that is returned by the expression. You can also leave it off and have the expression return the unit.

Non-property Attributes

Remember how property bindings bind directly to the property of an element? What happens when you want to set the value of an attribute that is not a property? There are some situations where attributes don’t have a corresponding property to set, but Angular has a way to manage this.

Aria attributes are used to indicate information to assistive devices about elements, such as aria-required which marks an input as required for for submission. Normally you would use attribute like this:

<input id="username" type="text" aria-required="true" />

Imagine that this field might not always be required, because your form may require giving a username or an email depending on the situation. If you tried to do aria-required="{{isRequired()}}" or [aria-required]="isRequired()", you’d get a template parsing error. Since this attribute is not a property, it cannot be directly bound to.

The workaround is using the special attribute binding syntax, which looks just like a property binding but you put the name of the attribute in the brackets with the prefix attr. like this:

<input id="username" type="text" [attr.aria-required]="isRequired()" />

Angular will now bind to the attribute and not the non-existent property. There aren’t very many attributes that are not also properties, but if you come across a template parse error saying your binding isn’t a known native property, then you’re probably binding to one of these attributes.

That summarizes the various property bindings available in Angular and the use cases for each of the different variations. You’ll use bindings so often that it will become second nature when you see the brackets that they are a binding from a component to an element property.

Angular 2 in Action BookGet Angular 2 in Action for 39% off! Use the code adendz during checkout.

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:
angular 2.0 ,binding ,angular ,angular applications

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}