Create your account

Already have an account? Login here

Note: By joining, you will receive periodic emails from Coursetro. You can unsubscribe from these emails.

Create account

Angular 4 Property Binding Tutorial

By Gary simon - Apr 01, 2017

Ready to build Awesome Angular Apps?

A Free Course, Free Tutorials and Full App Development Courses!

Great! Check your email

I've just sent you the first email to get you started.

Property binding simply means you're passing data from the component class and setting the value of a given element in the view. Property binding is one way, in that the data is transferred from the component to the class.

The benefit of property binding is that it allows you to control element property values from the component and change them whenever needed.

Let's take a closer look at property binding based on the previous lesson from the course.

First, if you prefer watching a video

Be sure to subscribe to the Coursetro Youtube Channel for more awesome dev videos!

Property Binding Example

There are 3 ways to define a property binding in Angular:

  <img src="{{ angularLogo }}">
  <img [src]="angularLogo">
  <img bind-src="angularLogo">
  1. You can use interpolation to define the value, as long as the value you're defining is a string. If it's not, you must use method 2 or 3 below.
  2. The most common method to define property binding is by wrapping brackets around an element property and binding it to a component property.
  3. Adding bind- before the element property also achieves the same thing.

To make this work, we just have to define angularLogo in the component property:

export class AppComponent {
  
  angularLogo = 'https://angular.io/resources/images/logos/angular2/angular.png';

}

After saving and running ng serve on the command line, you'll see that the view shows 3 logos, as all 3 img elements work.

Property Binding on the Disabled Attribute

Another common use-case for property binding is on an input element's disabled attribute. It allows you to control when a given input element should be enabled or disabled.

Add the following to the template:

<button [disabled]="buttonStatus">My Button</button>

And add the buttonStatus property in the component class:

buttonStatus = true;

Because buttonStatus is true, the disabled attribute is applied to the button. If you change it to false, it becomes clickable.

You can also define a different template expression:

<button [disabled]="buttonStatus == 'enabled'">My Button</button>

And change the buttonStatus property to:

buttonStatus = 'enabled';

We'll see this works too, as the button is disabled.

Conclusion

This, in a nutshell, is how property binding works. To recap:

  • Property binding allows you to define element attribute values from the component class.
  • It is one-way data binding, as you can only set data from the component to the view.

 


Share this post




Say something about this awesome post!