How to create login in ionic 2 with show/hide password

JSN picture JSN · Oct 18, 2017 · Viewed 16.5k times · Source

I wanted to create a design like this using ionic 2 -> https://codepen.io/Floky87/pen/bVopyZ

Which is a login functionality that has a hide/show password.

Here's my HTML code

<ion-header>

  <ion-navbar>
    <ion-title>Login</ion-title>
  </ion-navbar>

</ion-header>


<ion-content padding>
<ion-item>
      <ion-label floating primary>Username</ion-label>
      <ion-input type="text"></ion-input>
</ion-item> 
<ion-item>
      <ion-label floating primary>Password</ion-label>
      <ion-input type="password"></ion-input>
      <ion-icon name="eye" item-right (click)="showHide()"></ion-icon>
</ion-item> 
</ion-content>

And Here's the result -> http://prntscr.com/gz12xg

Here's my .ts code

import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';

@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {

  constructor(public navCtrl: NavController, public navParams: NavParams) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad LoginPage');
  }
  showHide() {
    console.log('hi');
  }

}

The Problem is, the eye icon, is not clickable. No log from the console.

When I click the eye icon, it only allows me to input from the password field.

Anybody can help me? I just want the eye icon to be clickable.

Answer

Azam Alvi picture Azam Alvi · Mar 4, 2018

You can do like below in your .ts file write this code

 passwordType: string = 'password';
 passwordIcon: string = 'eye-off';

 hideShowPassword() {
     this.passwordType = this.passwordType === 'text' ? 'password' : 'text';
     this.passwordIcon = this.passwordIcon === 'eye-off' ? 'eye' : 'eye-off';
 }

in your .html write this

<ion-item>
    <ion-label floating>Password</ion-label>
    <ion-input formControlName="password" [type]="passwordType" clearOnEdit="false"></ion-input>
    <ion-icon item-end [name]="passwordIcon" class="passwordIcon" (click)='hideShowPassword()'></ion-icon>
</ion-item>

and this will be your .scss code. Change according to your need

.passwordIcon{
   font-size:2rem !important;
   position: relative !important;
   top: 22px !important;
   margin: 0 auto !important;
}