Property Binding in Angular

Property Binding[property]

Property binding is an effective way of binding data in Angular. It is done using [] square brackets. The property of an HTML element is bind to the property in the component class. Property binding is unidirectional. The binding is from component class to the HTML element property. Under the hood, interpolation also works as property binding in Angular.
To bind a property of a dom element to a field or property in our component class is termed as property binding. Any changes in the component field will update the DOM. Any change in DOM will not reflect back into the component.
Now we will see some examples of property binding in Angular.
In the below example we have used interpolation({{...}}). It works as property binding under the hood. 

@Component({
  selector: 'app-button',
  template: `
     <h1>{{title}}</h1>
     <img src= "{{imageUrl}}" />'

export class AppButtonComponent { 
   title = "Property Binding Examples";
   imageUrl = "https://www.dummyurl.com"
   }

Now we will see the same example with property binding syntax. In the above example, we have used the DOM property of h1 tag i.e. textContent to set it to title property of the component class. Generally, when we want to render texts we will prefer using string interpolation. Whenever we want to add text to headings, paragraphs, divs, and spans. 

@Component({
  selector: 'app-button',
  template: `
     <h1 [textContent]="title"></h1>
     <img [src]="imageUrl"/>'

export class AppButtonComponent { 
   title = "Property Binding Examples";
   imageUrl = "https://www.dummyurl.com"
   }

In the same way, we will use property binding to disable or enable a button using a field in the component class. We will bind the button to disable state based on the isDisable property.

@Component({
  selector: 'app-button',
  template: `
   <button [disabled]="isDisable">Disabled Button</button>'

export class AppButtonComponent { 
     isDisable:boolean = true; // On Changing the value from true to false
   }

We can also add bind- before the element property also defines property binding as follows. 

<img bind-src='imageUrl' />
<p bind-innerHTML='Hello Anguar!'></p>

Points to Remember

While using property binding, we should take care of the following points:
  • The value in the template expression should evaluate to the value type which is expected by the target property. If the target property expects string, then expression should return string. If the target expects the number, then the number should be returned.
  • Never forget to use the square brackets[] around the property. Square braces will indicate Angular to evaluate the expression. If we will not use square brackets, Angular will not evaluate the string and take it as a constant value.

Comments