Angular Data Binding

Angular Data Binding

Databinding is an incredible element of Angular. Precise Databinding is utilized for correspondence. It is utilized to impart between your TypeScript code and the other part which is displayed to the clients for example HTML format.

Databinding is fundamental since when we compose the code in TypeScript, it is assembled to JavaScript and the outcome is displayed on HTML design. In this manner, to show the right and unconstrained outcome to the clients, a legitimate correspondence is important. That is the reason databinding is utilized in Angular.

Angular Event Binding

Angular Directives

There is two type of data binding:

  1. One-way databinding

    One way databinding is a simple one way communication where HTML template is changed when we make changes in TypeScript code.

    In single direction databinding, the worth of the Model is utilized in the View (HTML page) yet you can’t refresh Model from the View. Rakish Interpolation/String Interpolation, Property Binding, and Event Binding are the case of single direction databinding.
  2. Two-way databinding

    Two-way restricting gives parts in your application an approach to share information. Utilize two-way restricting to tune in for occasions and update esteems at the same time among parent and youngster parts.

    Two-way data binding refers to sharing data between a component class and its template. If you change data in one place, it will automatically reflate at the other end. For example, if you change the value of the input box, then it will also update the value of the attached property in a component class.
import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-greet',
  template: `
  User Name: <input type="text" [(ngModel)]="userName" ><br/>
    {{userName}}`
})
export class GreetComponent implements OnInit {
  constructor() { }
  private _userName: string = "bill gates";
  get userName(): string {
    return this._userName;
  }
  set userName(val: string) {
    //do some extra work here
    this._userName = val;
  }
  ngOnInit(): void {
  }
}

Data binding using @Input() and @Output():

//src/app/app.component.html
<app-sizer [size]="fontSizePx" (sizeChange)="fontSizePx=$event"></app-sizer>
// src/app/app.component.t

fontSizePx = 16;
// src/app/sizer.component.html

<div>

  <button (click)="dec()" title="smaller">-</button>

  <button (click)="inc()" title="bigger">+</button>

  <label [style.font-size.px]="size">FontSize: {{size}}px</label>

</div>

What is Angular

Angular Installation

// src/app/sizer.component.ts

export class SizerComponent {

  @Input()  size!: number | string;

  @Output() sizeChange = new EventEmitter<number>();

  dec() { this.resize(-1); }

  inc() { this.resize(+1); }

  resize(delta: number) {

    this.size = Math.min(40, Math.max(8, +this.size + delta));

    this.sizeChange.emit(this.size);

  }

}