How to Show and Hide Password in Angular

When creating forms in Angular, especially those involving password fields, it's important to provide users with the option to show or hide their passwords. This feature improves usability by allowing users to verify their input, reducing the likelihood of errors. In this article, we'll walk through how to implement a show/hide password toggle in Angular.

Prerequisites

  • Basic understanding of Angular
  • Angular CLI installed
  • A project set up with Angular

Step 1. Set up your Angular Project

If you haven't already, create a new Angular project using Angular CLI.

ng new password-toggle
cd password-toggle
ng serve

Step 2. Create the Password Component

Generate a new component for the password input field.

ng generate component password-input

Step 3. Update the Password Component Template

Edit the password-input.component.html file to include the password input field and a button to toggle visibility.

<div class="password-container">
  <input 
    [type]="showPassword ? 'text' : 'password'" 
    [(ngModel)]="password" 
    placeholder="Enter your password"
  >
  <button 
    type="button" 
    (click)="togglePasswordVisibility()"
  >
    <i 
      class="fa" 
      [ngClass]="{'fa-eye': !showPassword, 'fa-eye-slash': showPassword}"
    ></i>
  </button>
</div>

Step 4. Implement the Toggle Logic

In the password-input.component.ts file, add the logic to toggle the password visibility.

import { Component } from '@angular/core';
@Component({
  selector: 'app-password-input',
  templateUrl: './password-input.component.html',
  styleUrls: ['./password-input.component.css']
})
export class PasswordInputComponent {
  password: string = '';
  showPassword: boolean = false;
  togglePasswordVisibility(): void {
    this.showPassword = !this.showPassword;
  }
}

Step 5. Style the Component

Add some basic styling to password-input.component.css.

.password-container {
  display: flex;
  align-items: center;
}
input {
  flex: 1;
  padding: 0.5rem;
  margin-right: 0.5rem;
}
button {
  padding: 0.5rem 1rem;
  cursor: pointer;
}

Step 6. Run your application

Make sure your application is running.

Open your browser and navigate to http://localhost:4200. You should see the password input field with a show/hide button.

Conclusion

In this article, we've created a simple Angular component to toggle the visibility of a password field. This small feature can greatly enhance the user experience by providing better control over form inputs.