如何使用 angular 2 或 angular 4 在单击按钮时交换文本输入值?

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

我有两个文本框 name1 和 name2,如果我单击“交换”按钮,填充这些文本框后,文本框的值应该交换。

点击交换按钮后

使用 ngModel 指令绑定输入

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;
      }
    }

示例:https://stackblitz.com/edit/swap

您可以使用引用变量来实现它,在 HTML 文件中

<input type='text' #v>
<input type="text" #v1>
<button (click)='x=v.value; v.value = v1.value; v1.value = x'>Swap</button>