Show/Hide Password Field In Angular Form

December 16, 2024 • • Published By • 2 minute read

In modern web applications, user experience is key, especially when it comes to forms. One common feature that improves usability is the ability to toggle the visibility of password input fields. By allowing users to show or hide their password, you can reduce frustration caused by typos while maintaining security. In this article, we’ll implement a password visibility toggle in an Angular form. This simple feature can greatly enhance the user experience.

Table of Contents

Password Field

In your form, you’ll have an input field for entering a password. The input type should be password to initially hide the value being typed in. Create a template variable on the input field called passwordField. We will reference this later in the component.

<input type="password" id="password" name="password" #passwordField>

Show Password Field

Let’s add a checkbox and label to the form to toggle the visibility of the password value. When the user clicks on the label/checkbox, it will call a method called togglePasswordVisibility.

<input type="checkbox" id="showPassword" (click)="togglePasswordVisibility()">
<label for="showPassword">Show Password</label>

Show/Hide Password Toggle

Within your form component, let’s import what we need.

import { ElementRef, ViewChild } from '@angular/core';

Create a variable called passwordField and decorate it with ViewChild, referencing the passwordField template variable we previously defined. Let’s also define its type as ElementRef, specifically an HTMLInputElement.

@ViewChild('passwordField') passwordField: ElementRef<HTMLInputElement>;

Now let’s create the togglePasswordVisibility method that gets called anytime someone clicks the Show Password label/checkbox. If the password field type is password, we’ll change it to text, allowing the user to see the actual value in the password field. If the password field type is text, we’ll change it back to password, hiding the password value.

togglePasswordVisibility() {
    const field = this.passwordField.nativeElement;

    if (field.type === 'password') {
        field.type = 'text';
    } else {
        field.type = 'password';
    }
}

Related Articles
About the Author

Front End Developer

https://nightwolf.dev