Search code examples
angularswap

How to swap text input values on clicking button using angular 2 or angular 4?


I have two text boxes name1 and name2, after filling those if I click swap it button the text box values should swap.

1

After clicking swap it button

2


Solution

  • Use ngModel directive binds an input

    component.html

    <input type="text" [(ngModel)]="demo" >
    <input type="text" [(ngModel)]="demo1" >
    <button (click)="onSwap(demo,demo1)">Swap</button>
    

    component.ts

     import { Component } from '@angular/core';   
        @Component({
          selector: 'my-app',
          templateUrl: './app.component.html',
          styleUrls: [ './app.component.css' ]
        })
        export class AppComponent  {
          name = 'Angular';
          demo;
          demo1;
          onSwap(demo,demo1){
            this.demo1=demo;
            this.demo=demo1;
          }
        }
    

    Example:https://stackblitz.com/edit/swap