Providing users with the option to show or hide their passwords in forms is a useful feature that improves usability and reduces errors. In this article, we'll walk through how to implement a show/hide password toggle in an AngularJS application.
Prerequisites
- Basic understanding of AngularJS
- AngularJS included in your project
Step 1. Set up your AngularJS Application
If you haven't already, set up a basic AngularJS application. Include AngularJS in your project.
<!DOCTYPE html>
<html ng-app="passwordToggleApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<div ng-controller="PasswordController">
<password-input></password-input>
</div>
<script src="app.js"></script>
<script src="password-input.component.js"></script>
</body>
</html>
Step 2. Create the AngularJS Module and Controller
Create an app.js file and define your AngularJS module and controller.
// app.js
angular.module('passwordToggleApp', [])
.controller('PasswordController', ['$scope', function($scope) {
// Controller logic if needed
}]);
Step 3. Create the Password Component
Create a password-input.component.js file and define your password-input component.
// password-input.component.js
angular.module('passwordToggleApp')
.component('passwordInput', {
template: `
<div class="password-container">
<input
type="{{ $ctrl.showPassword ? 'text' : 'password' }}"
ng-model="$ctrl.password"
placeholder="Enter your password"
>
<button
type="button"
ng-click="$ctrl.togglePasswordVisibility()"
>
{{ $ctrl.showPassword ? 'Hide' : 'Show' }}
</button>
</div>
`,
controller: function() {
this.password = '';
this.showPassword = false;
this.togglePasswordVisibility = function() {
this.showPassword = !this.showPassword;
};
}
});
Step 4. Style the Component
Add some basic styling to style.css (make sure to include this CSS file in your HTML).
.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 5. Use the Password Component in Your App
Include the password component in your main application view. The component is already included in index.html through the controller.
<!DOCTYPE html>
<html ng-app="passwordToggleApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div ng-controller="PasswordController">
<password-input></password-input>
</div>
<script src="app.js"></script>
<script src="password-input.component.js"></script>
</body>
</html>
Step 6. Run your application
Open your index.html file in a web browser. You should see the password input field with a show/hide button.
Conclusion
In this article, we've created a simple AngularJS 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.