To allow users to toggle the visibility of the password when they click on the eye icon, you can use Angular's data binding and event handling. Here's an updated version of your code that includes this functionality:
Updated HTML with Toggle Functionality
<div class="col-md-4">
<div class="form-group">
<label for="password">Password</label>
<div class="input-group">
<input
id="password"
class="form-control"
name="password"
formControlName="password"
placeholder="Enter User Password"
[type]="isPasswordVisible ? 'text' : 'password'"
[readonly]="addUserRequest.get('isLdap')?.value === true"
/>
<div class="input-group-append">
<span class="input-group-text" (click)="togglePasswordVisibility()">
<i class="fa" [ngClass]="isPasswordVisible ? 'fa-eye-slash' : 'fa-eye'"></i>
</span>
</div>
</div>
</div>
</div>
Component Class
In your Angular component TypeScript file, you need to define the isPasswordVisible variable and the togglePasswordVisibility() method:
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'your-selector',
templateUrl: './your-template.html',
styleUrls: ['./your-style.css']
})
export class YourComponent {
addUserRequest: FormGroup;
isPasswordVisible: boolean = false;
constructor(private fb: FormBuilder) {
// Initialize your form group here
this.addUserRequest = this.fb.group({
password: [''],
// ... other form controls
});
}
togglePasswordVisibility() {
this.isPasswordVisible = !this.isPasswordVisible;
}
}
Explanation
-
Toggle Visibility:
- We create a variable
isPasswordVisible in the component class to track whether the password should be visible or not.
- The
togglePasswordVisibility() method switches the value of isPasswordVisible between true and false when the eye icon is clicked.
-
Dynamic Input Type:
- The input type is dynamically set using
[type]="isPasswordVisible ? 'text' : 'password'", so it switches between showing the password as plain text or hiding it.
-
Dynamic Icon:
- The eye icon is conditionally rendered using
[ngClass]="isPasswordVisible ? 'fa-eye-slash' : 'fa-eye'" to switch between the eye and eye-slash icons based on the visibility state.
Now, when the user clicks the eye icon, the password will toggle between being visible and hidden.