Introduction Integrating a Syncfusion JavaScript Pivot Table into a Blazor web application significantly enhances the data analysis capabilities. This is achievable by using a JavaScript interop that invokes JavaScript methods from the Blazor web application. In this article, we will guide you through the procedure, providing a step-by-step example. Step 1: Create an HTML element First, you must place a div element on your razor page (i.e., Index.razor), where the Pivot Table will be displayed. The id attribute of the div should be designated as a unique identifier to ascertain that JavaScript initializes the Pivot Table in this specific element correctly. Here is a code example of how you can create an HTML div element: [index.razor] @page "/" <div class="control-section"> <div class="content-wrapper pivot-container"> <div id="@ID" class="pivot-table"></div> </div> </div> [index.razor.cs] public partial class Index { private string ID = "PivotTable"; } Step 2: Defining the data source After creating the HTML div element, it is necessary to define the data source in your Razor page (i.e., Index.razor.cs) to configure the pivot table control. This can be done by creating a class that represents the data structure, in this case, ProductDetails. This class should contain properties that represent the necessary data fields for the pivot table, such as “Sold”, “Amount”, “Products”, “Year”, and “Quarter”. Here is an example of how to define a data source for the pivot table using a class called ProductDetails in the razor page: [index.razor.cs] namespace BlazorApp1.Pages { public partial class Index { public class ProductDetails { // Define properties that represent the data fields public int Sold { get; set; } public double Amount { get; set; } public string Country { get; set; } public string Products { get; set; } public string Year { get; set; } public string Quarter { get; set; } // Method to generate a list of product details public static List<ProductDetails> GetProductData() { // Add product details to the list List<ProductDetails> productData = new List<ProductDetails>(); productData.Add(new ProductDetails { Sold = 31, Amount = 52824, Country = "France", Products = "Mountain Bikes", Year = "FY 2015", Quarter = "Q1" }); // ... additional data reference return productData; } } } } Step 3: Serialize the data source After you have determined the necessary data source, you will need to convert it into a JSON string. This conversion is essential for the JavaScript code to accurately read and use the data within the Pivot Table. This can be accomplished by using the JsonSerializer.Serialize method within the OnInitializedAsync lifecycle method. Here is an example of how to convert a data source into JSON format: [index.razor.cs] using System.Text.Json; namespace BlazorApp1.Pages { public partial class Index { protected List<ProductDetails> Data { get; set; } private string dataSource; protected override async Task OnInitializedAsync() { // Assuming GetProductData is a static method that returns a list of ProductDetails. Data = ProductDetails.GetProductData(); // Serialize the Data list to a JSON string. dataSource = JsonSerializer.Serialize(Data); } } } Step 4: Add stylesheet and script resources Before initializing the pivot table, you need to include the Syncfusion styles and scripts in your ~/Pages/Host.cshtml file. This is typically done by adding the references inside the <head> tag of the ~/Pages/Host.cshtml file. Here is the code snippet how you can include the styles and scripts resources: [Host.cshtml] <!-- Syncfusion javascript control styles --> <link rel="stylesheet" href="https://cdn.syncfusion.com/ej2/24.1.41/fluent.css" /> <!-- Syncfusion javascript control scripts --> <script src="https://cdn.syncfusion.com/ej2/24.1.44/dist/ej2.min.js" type="text/javascript"></script> Step 5: Configure the javascript pivot table control Once you’ve included the necessary references, you’ll need to create a JavaScript file (e.g., pivotview.js) and define a function called integratePivotTable. This function takes the ID of the DOM element and the serialized data as arguments. Within this function, initialize the pivot view control with serialized data from the Blazor web application. [pivotview.js] function integratePivotTable(id, data) { // Parse the incoming data from a JSON string into an object var pivotData = JSON.parse(data); // Initialize pivot table component var pivotTableObj = new ej.pivotview.PivotView({ // Configure the data source settings for the pivot table dataSourceSettings: { // Assign the parsed data here dataSource: pivotData columns: [{ name: 'Year' }, { name: 'Quarter' }], values: [{ name: 'Sold', caption: 'Units Sold' }, { name: 'Amount', caption: 'Sold Amount'}], rows: [{ name: 'Country' }, { name: 'Products' }], }, width: '100%', height: 290, gridSettings: { columnWidth: 140 }, showFieldList: true }); // Append the pivot table to the DOM element with the specified ID pivotTableObj.appendTo('#' + id); } In the code example mentioned, we parse the retrieved data into a JavaScript object within the integratePivotTable method. Following this, we initialize pivot table component using ej.pivotview.PivotView() instance and assign the parsed data to the dataSource property of the dataSourceSettings. Subsequently we added the fields to row, column, values axes. Finally we appended this pivot table instance to the retrieved DOM element using the appendTo method. This action will render the pivot table in the Blazor web application. Step 6: Include the JavaScript file in your Blazor application Once you have initialized the pivot table in the pivotview.js file, you must reference it within the <body> tag of the ~/Pages/Host.cshtml file. Here’s an example of how you can accomplish this: [Host.cshtml] <html> <body> <script src="scripts/pivotview.js"></script> </body> </html> Step 7: Invoke JavaScript method in razor page Once you’ve included the pivotview.js file, you can invoke the integratePivotTable method on your razor page (i.e., Index.razor.cs) using JavaScript interop. Below is an example of how you can invoke the integratePivotTable method in your razor file: [Index.razor] using Microsoft.JSInterop; namespace BlazorApp1.Pages { public partial class Index { // Inject the IJSRuntime service that allows invoking JavaScript method [Inject] protected IJSRuntime JSRuntime { get; set; } protected override async Task OnAfterRenderAsync(bool firstRender) { // Here we we ensure the JavaScript method is only called once after the component is first rendered. if(firstRender) { // Invoking the 'integratePivotTable' JavaScript method and passing the ID and Serialized dataSource as parameters await JSRuntime.InvokeVoidAsync("integratePivotTable", ID, dataSource); } } } } In the above code, we first injected the IJSRuntime service using the [Inject] attribute. This service allows us to interact with JavaScript code from our razor page. Subsequently, within the OnAfterRenderAsync lifecycle method, we checked if it was the first render of the razor component by using the firstRender parameter. If this is indeed the first render, we used the InvokeVoidAsync method to invoke the integratePivotTable JavaScript method, passing the ID of the DOM element and the serialized data as parameters. This action integrates the JavaScript pivot table into a Blazor web application. Step 8: Run your application Now, compile and run your Blazor project you can see that the Syncfusion JavaScript Pivot Table component has been integrated and is functioning within your Blazor web application. The following screenshot portrays the results of the code snippets mentioned above, You can refer to this GitHub sample for a practical demonstration of this code. Conclusion I hope you enjoyed learning how to to integrate a JavaScript Pivot Table into a Blazor web application. You can also refer to our JavaScript Pivot Table feature tour page to learn about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our Pivot Table example to understand how to create and manipulate data. For current customers, you can check out our components on the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls. If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!
Introduction In certain situations, you may want to copy the contents of a Blazor Pivot Table to the clipboard. This feature can be particularly useful for copying the data for use in other applications such as Excel or text files. You can achieve this by using JavaScript Interop with an external button click. In this article, we will guide you through the process with a step-by-step example. Step-by-step implementation Step 1: JavaScript Interop for copying the content to clipboard First, you need to create a JavaScript file (i.e., clipboard.js) and define the copyToClipboard asynchronous function that processes the clipboard operation. This function takes the ID of the pivot table as a parameter to identify the table within the DOM (Document Object Model). [Clipboard.js] async function copyToClipboard(ID) { try { var text = ""; //To get the pivot table element by using it's ID var Element = document.getElementById(ID); //Here we get the column headers var cl = Element.getElementsByClassName("e-columnheader"); for (var i = 0; i < cl.length; i++) { if (i != 0) { var inner = "\t\t"; for (var j = 0; j < cl[i].children.length; j++) { inner += cl[i].children[j].innerText; for (var x = 0; x < cl[i].children[j].ariaColSpan; x++) { inner+= "\t "; } } } // Here we frame the column headers as text string text = text + inner + '\n'; } } var cls = Element.getElementsByClassName("e-table"); // Here we retrieve the table values var tablecontent = cls[cls.length - 1].innerText.replace(/\t/g, '\t\t'); var linesArray = tablecontent.split('\n'); // Here we retrieve the row headers var rowArray = cls[cls.length - 2].innerText.split('\n'); for (var k = 0; k < linesArray.length; k++) { // Here we frame the row headers and table values as text string along with column headers if (rowArray[k].length > 8) { text = text + rowArray[k] + '\t' + linesArray[k] + '\n'; } else { text = text + rowArray[k] + '\t\t' + linesArray[k] + '\n'; } } await navigator.clipboard.writeText(text); } catch (err) { console.error("Unable to copy text to clipboard:", err); } } In this function, the provided ID is used to retrieve the pivot table element. We then extract all the column headers, table values, and row headers from the same element by accessing their respective class names(i.e., e-columnheader and e-table) through the getElementsByClassName method. The retrieved table content is subsequently formatted as a text string. Finally, the constructed text is written into the clipboard using the navigator.clipboard.writeText method. Step 2: Include the script in your host file To use JavaScript Interop in a Blazor application, you need to refer to the JavaScript file (i.e., clipboard.js) in your host file (i.e., Host.cshtml). Below is an example of how to refer to the JavaScript file in your host page. [Host.cshtml] <html> <body> // Here we refered the clipboard script file <script src="scripts/clipboard.js"></script> </body> </html> Step 3: Invoke JavaScript function in Blazor Once your JavaScript Interop is set up, you can invoke the copyToClipboard function in your Blazor file (Index.razor) by clicking an external button. This action will copy the content of the pivot table to your system clipboard. It’s important to note that the copied content will be in a table structure, similar to the original pivot table. Below is an example of how to call the copyToClipboard method in your razor file. [Index.razor] @inject IJSRuntime JSRuntime <sfbutton> Copy Data </sfbutton> <sfpivotview id="@ID" @ref="pivot"> </sfpivotview> @code { private string ID= "Pivot"; private async Task Copy() { // Here we called the copyToClipboard method await JSRuntime.InvokeVoidAsync("copyToClipboard",ID); } } In the code snippet above, we used IJSRuntime interface to invoke the JavaScript copyToClipboard method from a Blazor application. The following screenshot portrays the results of the code snippet mentioned above, Screenshot View Sample in GitHub Conclusion I hope you enjoyed learning how to copy content from Blazor Pivot Table to clipboard You can also refer to our Pivot Table feature tour page to learn about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our Pivot Table example to understand how to create and manipulate data. For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls. If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!