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

Data Binding in Angular

DZone 's Guide to

Data Binding in Angular

We look into the four ways developers can work with data binding in the Angular framework.

· Web Dev Zone ·
Free Resource

Data binding in Angular refers to the binding of data from a component class instance to its user-facing template.

There are four ways to bind data in Angular: Interpolation, Property Binding, Event Binding, and Two-way Data Binding.

Interpolation

Interpolation displays the value of a particular variable in the view. It uses double curly braces to display values, e.g.  {{}}. We can also write mathematical expressions, string concatenation operations, JavaScript predefined methods, and call user defined methods inside these {{}} braces.

Example:

import { Component } from '@angular/core';

@Component({

  selector: 'app-demo',

  template: `

  <h2>{{'Stored variable value:'+storedVar}}</h2>

  <h2>{{2+2}}</h2>

  <h2>{{name.toUpperCase()}}</h2>`,

  styleUrls: ['./animation.component.css']

})

export class DemoComponent {

  constructor() { }

   public storedVar = 20;­­­­

   public name = 'angular';

}

Property Binding

Property binding binds values to DOM properties. There is a limitation to interpolation in that it can only work with string values and there are some boolean HTML properties (like disabled) that we sometimes need to bind to.

Example:

@Component({

  selector: 'app-demo',

  template: `

 <input [id]="textId" >`,

  })

export class DemoComponent {

  constructor() { }

   public textId = 'textBox';

}

Event Binding

Event binding binds a function when an event is performed or, in other words, it is used to capture events.

Example:

@Component({

  selector: 'app-demo',

  template: `

 <button (click)="buttonClicked()">Click Me</button>`,

})

export class DemoComponent {

  public buttonClicked(){

    console.log('I am clicked');

  }

}

Two-Way Data Binding:

The syntax used for two-way data binding is called banana in box, i.e. [()]. Angular provides the ngModel directive to work with two-way data binding.

Note: For using ngModel  you must import FormsModule and add that to your mports.

Example:

@Component({

  selector: 'app-demo',

  template: `

 <input [(ngModel)]="name" type="text">

 <br>

 {{name}}`,})

export class DemoComponent {

  public ;

}

Conclusion

Data binding provides binding of data from a component to a template in different ways. We should use the appropriate method based on our requirements.

Topics:
interpolation ,data binding ,property binding ,angular tutorial ,web dev

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}