Adding a toggle button for viewing password in Ionic


#1

I want to add a button on the right end of a password <input> that will show or hide the password. Can this be achieved in Ionic?


#2

First, here’s the one way you should not do it: don’t change the input type from “text” to “password” and back. As a matter of principle, never reduce security, even if it’s simply a form input element.

Here’s the way I went about it…

Home.html

        <ion-card-content>
            <form>
                <div id="alpha">
                    <ion-item>
                        <ion-input placeholder="password" clearInput [(ngModel)]="password"></ion-input>
                    </ion-item>
                </div>
                <div id="bullets" style="display:none;">
                    <ion-item>
                        <ion-input placeholder="password" type="password" [(ngModel)]="password"></ion-input>
                    </ion-item>
                </div>
            </form>
            <button (click)="toggle()">Toggle</button>
        </ion-card-content>
    </ion-card>

Home.js

import {Page} from 'ionic-angular';

@Page({
    templateUrl: 'build/pages/home/home.html'
})
export class HomePage {
    constructor() {
        this.password = "123";
    }

    toggle() {
        let divAlpha = document.getElementById('alpha');
        let divBullets = document.getElementById('bullets');

        if (divAlpha.style.display == 'none') {
            divAlpha.style.display = 'block';
            divBullets.style.display = 'none';
        }
        else {
            divAlpha.style.display = 'none';
            divBullets.style.display = 'block';
        }
    }
}

#3

For Ionic v1, you can use: