Use Angular 4 Property Binding In Less Than 5 Minutes


Hey Techies, this page will guide you over Angular 4 Property Binding.

There are basically two ways of binding.

One, is bind the data from template to the component. Event Binding

Other way, is to bind the data from component to the template (i.e. view) of the user.

What is Angular 4 property binding?

Property binding is a way, in that the data is transferred from the component to the template.

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

How property binding works in angular 4?

Let’s bind the value of textbox from the component by using property binding in below example.

<input type="text" value="{{ sayHello() }}" />

Here, whatever will be returned by the component function named sayHello that would be bind to the input element.

Moreover, below image explains how the property binding works actually in Angular 4 app.

Angular 4 Property Binding Example

Three ways to use Angular 4 Property Binding

Technically there are 3 ways to bind properties.

  • String Interpolation – {{ expression }} – It sets and renders the value from component and it converts the expression into string.

  • Property Binding – [target]=”expression” – does the same thing by getting the value from component to template, but it would be best, if you want to bind the expression that is other than the string (for example – boolean).

    <input type="text" [value]="sayHello()" />
  • bind-target=”expression” – This is not a regular way of using. Just adding bind before the element, it does the same thing.

    <input type="text" bind-value="sayHello()" />

Let’s do some common ways of property binding

  • Class binding

    You can add/remove a class on the element by passing the value from component to the view.

    [class.special]="isSpecial">The class binding is special
  • Style binding

    Similar to class, you can change the styles of the elements in the template based on the dynamic values passed by the component.

    <button [style.color]="isStopped ? 'red' : 'blue'">red</button>
  • Attribute binding

    You can set the value from component and that will affect to the view only.

    Component Class

    buttonStatus = true;

    HTML template

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

To conclude,

  • There are mainly three ways to use Angular 4 property binding feature.
  • You can also achieve class, styles, attributes and many more using angular 4 property binding.
  • It’s a one-way binding, binds the data from component to the view.

To further dig into propery binding, visit, Property Binding By Angular

Feel free to share your suggestions/questions, right here below the post as comments!

Leave a Reply

Notify of