diff --git a/knowledge-base/autocomplete-copy-text-itemtemplate.md b/knowledge-base/autocomplete-copy-text-itemtemplate.md new file mode 100644 index 000000000..d19bd3d57 --- /dev/null +++ b/knowledge-base/autocomplete-copy-text-itemtemplate.md @@ -0,0 +1,106 @@ +--- +title: How to Copy Text from an ItemTemplate +description: Learn how to allow users to copy text from the ItemTemplate in the AutoComplete for Blazor component. +type: how-to +page_title: How to Enable Text Copy in AutoComplete Dropdown Blazor +slug: autocomplete-kb-copy-text-itemtemplate +tags: blazor, autocomplete, itemtemplate, clipboard, copy, paste +res_type: kb +ticketid: 1689288 +--- + +## Environment + + + + + + + + + + + +
ProductAutoComplete for BlazorDropDownList for BlazorComboBox for BlazorMultiSelect for Blazor
+ +## Description + +I want to allow users to copy the text from the dropdown list in the [AutoComplete component](slug:autocomplete-overview). + +## Solution + +To enable text copying from the dropdown list in the AutoComplete, use the `ItemTemplate` to display the desired text alongside a button that uses JavaScript and the Clipboard API for copying. Here’s an example implementation: + +````RAZOR +@inject IJSRuntime JS + + + + + + @{ + var text = context.ToString(); + } +
+ @text + +
+
+
+ +@code { + private string Role { get; set; } + private List AutoCompleteData { get; set; } + private List SourceData { get; set; } = new() + { + "Manager", "Developer", "QA", "Technical Writer", "Support Engineer", "Sales Agent", "Architect", "Designer" + }; + + protected override void OnInitialized() + { + AutoCompleteData = SourceData; + } + + private void OnCheckBoxChangeHandler() + { + AutoCompleteData = new List(SourceData); + } + + private async Task CopyToClipboard(string text) + { + try + { + var isSupported = await JS.InvokeAsync("eval", "!!(navigator.clipboard && navigator.clipboard.writeText)"); + if (isSupported) + { + await JS.InvokeVoidAsync("navigator.clipboard.writeText", text); + } + else + { + Console.WriteLine("Clipboard API not supported in this browser."); + // Optionally show a notification to the user + } + } + catch (Exception ex) + { + Console.Error.WriteLine($"Clipboard copy failed: {ex.Message}"); + // Optionally show a fallback UI message to the user + } + } +} +```` + +## See Also + +* [AutoComplete Documentation](slug:autocomplete-overview) +* [Clipboard API Documentation](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API) +* [Blazor JavaScript Interoperability](https://docs.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability)