Angular 2将同一单击事件绑定到多个元素并更改类

时间:2018-10-01 07:40:46

标签: angular angular2-template

仅当我具有多个具有相同名称的(单击)事件时,如果仅通过(单击)事件才具有该元素,如何更改其类?这可能吗? (请参见下面的代码)

还是应该区分其(单击)事件名称?这不是多余的吗?

HTML

<mat-form-field class="col-md-12">
   <label><i class="fa fa-lock"></i> CURRENT PASSWORD</label>
   <input matInput type="password" name="current_password">
   <i class="fa right" [ngClass]="{'fa-eye': !displayPassword, 'fa-eye-slash': displayPassword}" (click)="showPassword($event)"></i>
</mat-form-field>
<mat-form-field class="col-md-12">
   <label><i class="fa fa-lock"></i> NEW PASSWORD</label>
   <input matInput type="password" name="new_pass">
   <i class="fa right" [ngClass]="{'fa-eye': !displayPassword, 'fa-eye-slash': displayPassword}" (click)="showPassword($event)"></i>
</mat-form-field>
<mat-form-field class="col-md-12">
   <label><i class="fa fa-lock"></i> CONFIRM NEW PASSWORD</label>
   <input matInput type="password" name="con_new_pass">
   <i class="fa right" [ngClass]="{'fa-eye': !displayPassword, 'fa-eye-slash': displayPassword}" (click)="showPassword($event)"></i>
</mat-form-field>

TS

public displayPassword = false;

showPassword(event){
  if(event.displayPassword == false){
    event.displayPassword = true;
  }else{
    event.displayPassword = false;
  }
}

2 个答案:

答案 0 :(得分:1)

使用不同的布尔值
这应该工作:

<mat-form-field class="col-md-12">
   <label><i class="fa fa-lock"></i> CURRENT PASSWORD</label>
   <input matInput type="password" name="current_password">
   <i class="fa right" [ngClass]="{'fa-eye': !displayCurrentPassword, 'fa-eye-slash': displayCurrentPassword}" (click)="displayCurrentPassword=!displayCurrentPassword"></i>
</mat-form-field>
<mat-form-field class="col-md-12">
   <label><i class="fa fa-lock"></i> NEW PASSWORD</label>
   <input matInput type="password" name="new_pass">
   <i class="fa right" [ngClass]="{'fa-eye': !displayNewPassword, 'fa-eye-slash': displayNewPassword}" (click)="displayNewPassword=!displayNewPassword"></i>
</mat-form-field>
<mat-form-field class="col-md-12">
   <label><i class="fa fa-lock"></i> CONFIRM NEW PASSWORD</label>
   <input matInput type="password" name="con_new_pass">
   <i class="fa right" [ngClass]="{'fa-eye': !displayConfirmPassword, 'fa-eye-slash': displayConfirmPassword}" (click)="displayConfirmPassword=!displayConfirmPassword"></i>
</mat-form-field>

在TS中:

displayConfirmPassword = false;
displayNewPassword=false;
displayCurrentPassword=false;

答案 1 :(得分:0)

您在event方法中拥有showPassword,因此可以完全控制单击的元素,可以使用jQuery将类添加/删除到元素中

if($(event.target).hasClass('fa-eye-slash')){
  $(event.target).removeClass('fa-eye-slash').addClass('fa-eye');
}
else{
  $(event.target).removeClass('fa-eye').addClass('fa-eye-slash');
}