DEV Community

Jozsef
Jozsef

Posted on

Angular Data Bindings

#prerequisite

ng new property-binding-demo
ng g c home

  • String Interpolation

In Angular, Interpolation is used to display data from component to view (DOM).

The code in your home.component.ts

public appName : string  = 'My first string interpolation';
Enter fullscreen mode Exit fullscreen mode

The home.component.html should look like as follows

<h3>String interpolation</h3>
<p>{{appName}}</p>
Enter fullscreen mode Exit fullscreen mode
  • Event Binding If there is any action (mouse click or keyboard action) then the event will be raised. We have different ways to bind an event to DOM element.

The home.component.ts has a function which receive an event parameter

public logEvent(event) {
  console.log(event.target)
}
Enter fullscreen mode Exit fullscreen mode

The home.component.html has to call the logEvent() method as follows

<h3>Event Binding</h3>
<button (click)="logEvent($event)">Click ME</button>
Enter fullscreen mode Exit fullscreen mode
  • Property binding This used to bind the data from property of a component to DOM elements. It is denoted by [].
public userName : string  = 'Bob';
Enter fullscreen mode Exit fullscreen mode

In the home.component.html input element will be initialized with userName value

<h3>Property binding</h3>
<input type="text" [value]="userName">
Enter fullscreen mode Exit fullscreen mode
  • Class Binding

It helps to create component with dinamic styling.

Define css classes in in home.component.css

.red {
    background-color: red;
}

.blue {
    background-color: blue;
}
Enter fullscreen mode Exit fullscreen mode

In home.component.ts declare a propery and bind one of the css class name and create a function which chnages its value.

public colorProperty : string = 'red';

public changeColor() {
    this.colorProperty === 'red' ? this.colorProperty = 'blue' : this.colorProperty ='red'
 }

Enter fullscreen mode Exit fullscreen mode

In home.component.html bind from component to view as below

<h3>Style binding</h3>
<div [style.color]="colorProperty">
  Style binding content
</div>
<button (click)='changeColor()'>Change Color</button>
Enter fullscreen mode Exit fullscreen mode
  • Two-way Binding

Is a two-way interaction, data flows in both ways (from component to views and views to component).
FormModule do the necessary setup to enable two-way data binding, therefore it is necessary to import.

Create a separate property for twoWayBinding in home.component.ts

 public twoWayBinding : string = 'init';
Enter fullscreen mode Exit fullscreen mode

Update HomeComponent view (home.component.html) as mentioned below

<h3>Two-way data binding</h3>
<input type="text" [(ngModel)]="twoWayBinding"/>
{{twoWayBinding}}
Enter fullscreen mode Exit fullscreen mode

Property is bind to form control ngModeldirective and if you enter any text in the textbox, it will bind to the property.

Top comments (0)