DEV Community

Cover image for Show/Hide Password Field In Angular Form
nightwolfdev
nightwolfdev

Posted on • Originally published at nightwolf.dev

Show/Hide Password Field In Angular Form

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.

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Show/Hide Password Toggle

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

import { ElementRef, ViewChild } from '@angular/core';
Enter fullscreen mode Exit fullscreen mode

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>;
Enter fullscreen mode Exit fullscreen mode

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';
    }
}
Enter fullscreen mode Exit fullscreen mode

Visit our website at https://nightwolf.dev and follow us on X!

Top comments (0)