Create a Show / Hide Password Component in Ionic & Angular
Published in
2 min readOct 19, 2020
Add this show/hide password component to your Ionic Angular App in 3 simple steps.
Step 1 — Create the Angular component
- Create an Angular Component with a ContentChild IonInput.
- Add a toggle method that will be triggered when clicking the eye icon.
- This method will switch between showing the password text and the dots.
- Define a showPassword boolean var.
import { Component, ContentChild } from '@angular/core';
import { IonInput } from '@ionic/angular';@Component({
selector: 'app-show-hide-password',
templateUrl: './show-hide-password.component.html',
styleUrls: ['./show-hide-password.component.scss']
})
export class ShowHidePasswordComponent {
showPassword = false;@ContentChild(IonInput) input: IonInput;constructor() {}toggleShow() {
this.showPassword = !this.showPassword;
this.input.type = this.showPassword ? 'text' : 'password';
}
}
Step 2 — Add the html markup for the component
- Create a simple anchor with our toggle method binded to the click event.
- Change the icon between eye open and eye closed depending on the showPassword var.
<ng-content></ng-content>
<a class="type-toggle" (click)="toggleShow()">
<ion-icon class="show-option" [hidden]="showPassword" name="eye-off-outline"></ion-icon>
<ion-icon class="hide-option" [hidden]="!showPassword" name="eye-outline"></ion-icon>
</a>
This is my show-hide-password.component.scss, to add some styles.
:host {
display: flex;
width: 100%;
align-items: center;.type-toggle {
padding-inline-start: 0.5rem;.show-option,
.hide-option {
font-size: 1.2rem;
display: block;// In case you want to use text instead of icons
&:not(ion-icon) {
text-transform: uppercase;
font-size: 1rem;
}
}
}
}
Step 3 — Use the Show / Hide password component
Just use the component with a <ion-input> as a content child.
<ion-item>
<app-show-hide-password>
<ion-input type="password" placeholder="Password" formControlName="password"></ion-input>
</app-show-hide-password>
</ion-item>
That’s all.
That was easy right?
Go ahead and add it to your Ionic Framework App and show me the result.
Learn more about Ionic Framework!
Need help with the styling? Let me know in the comments.