7. Angular Data Binding - String Interpolation. Tutorial 7

 Typically in Angular, we data bind in some ways. Those are used as majors.

  1. Output Data
    • String Interpolation.    Syntax- {{data}}
    • Property Binding.         Syntax- [property]="data"
  2. Event Binding                    Syntax- (event) = "expression"
  3. Two-Way-Binding            Syntax- [(ngModel) = "data"]


1. Output Data - String Interpolation

It is very easy. In .ts file just assign and initialize the variables. And show data in the template. 

        Syntax in template : {{data}}


1. Output Data - Property Binding

    Type script file - 

import { Component } from '@angular/core';
@Component({
           selector: 'app-property-binding',
           templateUrl: './property-binding.component.html',
           styleUrl: './property-binding.component.css'
          })
export class PropertyBindingComponent {
       submitMessage = "User was not created.";
}

     HTML file - 

<p>Property Binding</p>
<p [innerInput]="submitMessage"></p>



2. Event Binding

Basically, Event Binding binds the data after the fire of any event.

The syntax like - (click)="fnAddUser()"    

// Here fnAddUser() function is calling while clicking on the button.

HTML -

import { Component } from '@angular/core';
@Component({
  selector: 'app-event-binding',
  templateUrl: './event-binding.component.html'
})
export class EventBindingComponent {
    enableBtn = true; // true, for initially button will be disable
    message = "User was not created.";

    // This method will call after two second of page load autometically
    constructor(){
      setTimeout(() => {
        this.enableBtn = false; // Button enable
      }, 2000);
    }

    // Button click action. Adding user.
    fnAddUser(){
      this.message = "User created successfully.";
    }
}


TypeScript - 

<p>Add New User</p>
<button class="btn btn-primary" [disabled]="enableBtn" (click)="fnAddUser()">Add User</button>
<p [innerHTML]="message"></p>

        

Structure of Code - 





3. Two-Way-Databinding

Important: In two-way binding we must import FormsModule Class in app.module.ts file

  imports: [
    BrowserModule,
    FormsModule
  ],




Now make two way data bind.

> component.login.ts file
export class AppComponent {
  username = '';
  password = '';
}
> component.login.html file
<input type="text" class="form-control" [(ngModel)]="username">
<input type="password" class="form-control" [(ngModel)]="password">

Example of two-way data binding


Post a Comment

0 Comments