How to add a password toggle icon to the SfTextBox component with Syncfusion Blazor
This article demonstrates how to append a password toggle icon to a SfTextBox
component in a Syncfusion Blazor application. The toggle icon allows users to show or hide their password input for better usability.
Implementation
To implement the password toggle functionality, you will need to use the AddIconAsync
method in the Created
event of the SfTextBox
. Below is a step-by-step guide and code snippets to help you set up this feature.
Step 1: Add SfTextBox to your Razor Page
In your Index.razor
file, include the SfTextBox
component with a reference, type, placeholder, and the Created
event.
@using Syncfusion.Blazor.Inputs
@inject IJSRuntime JSRuntime
<SfTextBox ID="passwordBox" @ref="TextBoxObj" Type="@TextBoxType" Placeholder="Enter Password" Created="@Created"></SfTextBox>
Step 2: Define the Component Code
Within the @code
block, define the SfTextBox
object, a boolean to track the visibility of the password, and the TextBoxType
property. Also, implement the Created
and PasswordClick
methods.
@code {
SfTextBox TextBoxObj;
bool IsPasswordVisible = false;
InputType TextBoxType => IsPasswordVisible ? InputType.Text : InputType.Password;
public async Task Created()
{
await TextBoxObj.AddIconAsync("prepend", "fa fa-eye-slash", new Dictionary<string, object>() { { "onclick", EventCallback.Factory.Create<MouseEventArgs>(this, PasswordClick) } });
}
public async Task PasswordClick()
{
await JSRuntime.InvokeAsync<object>("showhidePassword", "passwordBox");
IsPasswordVisible = !IsPasswordVisible;
}
}
Step 3: Add JavaScript for Toggle Functionality
In your _Layout.cshtml
file, add the JavaScript function showhidePassword
that toggles the password visibility and icon appearance.
<script>
function showhidePassword(textBoxId) {
const textBox = document.getElementById(textBoxId);
const icon = textBox.parentElement.querySelector('.e-input-group-icon');
icon.classList.toggle('fa-eye');
icon.classList.toggle('fa-eye-slash');
}
</script>
Step 4: Run and Test
Run your application and test the password toggle functionality by clicking on the appended icon in the SfTextBox
.
Sample and API Reference
For a complete example, you can download the sample project from the following link:
For more details on the SfTextBox
API, refer to the official documentation: