New to Telerik UI for BlazorStart a free 30-day trial

Reusable Grid Columns with Templates

Description

This knowledge base article answers the following questions:

  • How can I create a reusable GridColumn component in Blazor?
  • What is the best way to encapsulate GridColumn templates in a reusable component?

Environment

ProductGrid for Blazor

Solution

To create a reusable GridColumn component with templates, follow these steps:

  1. Define a custom column component that accepts parameters for the field, title, whether it uses templates, and the currently edited item.

  2. Within the custom component, conditionally render a GridColumn with or without templates based on the provided parameters.

RAZOR
<TelerikGrid Data="@MyData" EditMode="@GridEditMode.Incell" Pageable="true" OnUpdate="@UpdateHandler">
    <GridColumns>
        <CustomColumn TItem="@Employee" Field="@(nameof(Employee.ID))"></CustomColumn>
        <CustomColumn TItem="@Employee" Field="@(nameof(Employee.Name))"></CustomColumn>
        <CustomColumn TItem="@Employee" EditedEmployee="@CurrentlyEditedEmployee" IsTemplate="@true" Field=@nameof(Employee.RoleId) Title="Position"></CustomColumn>
    </GridColumns>
</TelerikGrid>

@code {
    private List<Employee> MyData { get; set; }
    private Employee CurrentlyEditedEmployee { get; set; }

    private async Task UpdateHandler(GridCommandEventArgs args)
    {
        Employee item = (Employee)args.Item;

        await MyService.Update(item);

        await GetGridData();
    }

    private async Task GetGridData()
    {
        MyData = await MyService.Read();
    }

    protected override async Task OnInitializedAsync()
    {
        await GetGridData();
    }

    public static class MyService
    {
        private static List<Employee> _data { get; set; } = new List<Employee>();

        public static async Task<List<Employee>> Read()
        {
            if (_data.Count < 1)
            {
                for (int i = 0; i < 50; i++)
                {
                    _data.Add(new Employee()
                    {
                        ID = i,
                        Name = "name " + i,
                        RoleId = i % 4
                    });
                }
            }

            return await Task.FromResult(_data);
        }

        public static async Task Update(Employee itemToUpdate)
        {
            var index = _data.FindIndex(i => i.ID == itemToUpdate.ID);
            if (index != -1)
            {
                _data[index] = itemToUpdate;
            }
        }
    }
}

See Also