I would like to implement a blazor mention component.So in a textbox when we type @ to have a dropdown with a list of possible choices. For the dropdown elements I would like to have a template with image and text in it.
Any ideas how could I start that?
At the end I ended up with the following code, I will improve it over time but it gives you the idea:
@code {
private string InputText { get; set; } = string.Empty;
private bool ShowSuggestions { get; set; } = false;
private List<string> Suggestions = new List<string> { "Alice", "Bob", "Charlie", "David" };
private List<string> FilteredSuggestions = new List<string>();
private void OnInputTextChanged()
{
if (InputText.Contains("@"))
{
ShowSuggestions = true;
var mentionText = InputText.Split('@').Last();
FilteredSuggestions = Suggestions.Where(s => s.StartsWith(mentionText, StringComparison.OrdinalIgnoreCase)).ToList();
}
else
{
ShowSuggestions = false;
}
}
private void OnSuggestionClicked(string suggestion)
{
var mentionText = InputText.Split('@').Last();
InputText = InputText.Replace("@" + mentionText, "@" + suggestion);
ShowSuggestions = false;
}
}
<div class="mention-container">
<textarea @bind-value="InputText" @bind-value:event="oninput" @oninput="OnInputTextChanged"></textarea>
@if (ShowSuggestions)
{
<div class="suggestions">
@foreach (var suggestion in FilteredSuggestions)
{
<div @onclick="() => OnSuggestionClicked(suggestion)">
@suggestion
</div>
}
</div>
}
</div>
<style>
.mention-container {
position: relative;
width: 300px;
}
.suggestions {
position: absolute;
width: 100%;
max-height: 100px;
overflow-y: auto;
border: 1px solid #ccc;
background-color: #fff;
}
.suggestions div {
padding: 5px;
cursor: pointer;
}
.suggestions div:hover {
background-color: #eee;
}
</style>