We can easily implement show or hide password functionality in an Angular 12/13 + applications.
Initial HTML:
<div class="mb-3">
<label for="exampleInputPassword1" class="form-label">Password</label>
<input type='password' class="form-control" id="exampleInputPassword1">
</div>
<button class="btn btn-primary"> Show Password</button>
The HTML code contains an input element of type password and a button. Its plain HTML and nothing Angular in it.
To Show or Hide the contents of an input element we can simply change its type from password to text or text to password. We can create a property in our ts file, based on which we either give password or text value to the input type. We can use the same property to either show ‘Show Password’ or ‘Hide Password’ button text. We can now toggle this property to true or false when the user clicks on the button by implementing event binding on the button.
Modified HTML:
<div class="mb-3">
<label for="exampleInputPassword1" class="form-label">Password</label>
<input [type]=" showPassword ? 'text' : 'password' " class="form-control" id="exampleInputPassword1">
</div>
<button class="btn btn-primary" (click)='showHidePassword()'> {{ showPassword ? 'Hide' : 'Show' }} Password</button>
TS file:
showPassword: boolean = false;
constructor() { }
ngOnInit(): void {
}
showHidePassword() {
this.showPassword = !this.showPassword;
}
Please note that, we can implement the same in many different ways in an Angular application, so the above code is not the only way of implementing this functionality. In this code, we implemented it without using any additional forms module and in the simplest way possible.
Please check this post if you want to implement the same using plain JavaScript
How to Implement Show / Hide Password in JavaScript without using any library or framework
Leave A Comment