首页 > 解决方案 > 如何将不同的参数发送到相同的函数以进行显示/隐藏

问题描述

我有三个带有单击按钮的密码输入框我只需要使用 fontawosme 图标显示或隐藏密码类型(文本或密码)。

下面是我尝试作为代码的代码:

ts.文件

changePasswordType(type) {
  if (type == 'oldPassword') {
    this.showPassword = !this.showPassword;
    this._pwdType = this.showPassword ? 'text' : 'password'
  } else if (type == 'newPassword') {
    this.newPassword = !this.newPassword;
    this._pwdType = this.newPassword ? 'text' : 'password'
  } else {
    this.confirmPassword = !this.confirmPassword;
    this._pwdType = this.confirmPassword ? 'text' : 'password'

  }
}

<div class="form-group position-relative">
  <label for="oldpassword" class="lable-title mb-0">Old Password</label>
  <input [type]="_pwdType" class="form-control" required name="old_password" [(ngModel)]="form.old_password" #old_password="ngModel" id="oldpassword">
  <button class="position-absolute hide-password" *ngIf="!showPassword" (click)="changePasswordType('oldPassword')">
              <i class="far fa-eye-slash"></i>
            </button>
  <button class="position-absolute hide-password " *ngIf="showPassword" (click)="changePasswordType('oldPassword')">
              <i class="far fa-eye"></i>
            </button>
</div>


<div class="form-group position-relative">
  <label for="newpassword" class="lable-title mb-0">New Password</label>
  <input [type]="_pwdType" class="form-control" required name="password" [(ngModel)]="form.password" #password="ngModel" id="newpassword">
  <button class="position-absolute hide-password" *ngIf="!newPassword" (click)="changePasswordType('newPassword')">
              <i class="far fa-eye-slash"></i>
            </button>
  <button class="position-absolute hide-password " *ngIf="newPassword" (click)="changePasswordType('newPassword')">
              <i class="far fa-eye"></i>
            </button>
</div>


<div class="form-group position-relative">
  <label for="conformpassword" class="lable-title mb-0">Confirm Password</label>
  <input [type]="_pwdType" class="form-control" required name="confirm_password" [(ngModel)]="form.confirm_password" #confirm_password="ngModel" id="conformpassword">
  <button class="position-absolute hide-password" *ngIf="!confirmPassword" (click)="changePasswordType('confirmPassword')">
              <i class="far fa-eye-slash"></i>
            </button>
  <button class="position-absolute hide-password " *ngIf="confirmPassword" (click)="changePasswordType('confirmPassword')">
              <i class="far fa-eye"></i>
            </button>
</div>

单击按钮时,所有三个输入框都将转换为输入文本或密码。我只需要当我单击一个按钮时,只有该按钮应显示类型文本或密码,并且图标应分别更改

标签: angular

解决方案


我还没有真正理解这个问题,但重构将是:

.ts

showPassword  = false;

并且在.html

<input [type]="showPassword ? 'password':'text'">
<button (click)="showPassword  = !showPassword  ">
    <i [ngClass]="{'far fa-eye-slash': !showPassword  , 'far fa-eye': showPassword  }"></i>
</button>

StackBlitz 上的工作代码,https: //stackblitz.com/edit/angular-372rjc


推荐阅读