New to Telerik UI for Blazor? Download free 30-day trial

Change Primary SplitButton On Click

Environment

Product SplitButton for Blazor

Description

This KB article answers the following questions:

  • How to use dynamic primary SplitButton action that changes on click?
  • How to make the clicked SplitButton item primary?
  • How to switch the SplitButton's default item after click, similar to the Create Pull Request button in GitHub?
  • How to create dynamic SplitButton that toggles its primary action when the user clicks on a dropdown item?

Solution

  1. Define a collection of objects that will act as a datasource for the SplitButton.
  2. Define a property that will store the current primary action of the SplitButton. Use this property to render the primary button Text and Icon.
  3. Remove the current primary button from the SplitButton datasource and render the remaining <SplitButtonItem> instances in a loop. Make sure to set their @key attribute to maintain correct component references.
  4. Change the primary SplitButton item in the OnClick handler of the button items in the dropdown.

Using dynamic primary SplitButton action

@* Change SplitButton primary action on click *@

<TelerikSplitButton Icon="@PrimaryButton.Icon"
                    OnClick="@( () => OnSplitButtonClick(PrimaryButton) )">
    <SplitButtonContent>@PrimaryButton.Text</SplitButtonContent>
    <SplitButtonItems>
        @{
            var secondaryButtons = AllSplitButtons.Where(x => x.Id != PrimaryButton.Id);
            foreach (var button in secondaryButtons)
            {
                <SplitButtonItem Icon="@button.Icon"
                                 OnClick="@( () => OnSplitButtonClick(button) )">
                    @button.Text
                </SplitButtonItem>
            }
        }
    </SplitButtonItems>
</TelerikSplitButton>

Last click action: @SplitButtonLog

@code {
    private List<SplitButtonModel> AllSplitButtons { get; set; } = new List<SplitButtonModel>() {
        new SplitButtonModel() { Id = 1, Text = "Paste", Icon = SvgIcon.Clipboard },
        new SplitButtonModel() { Id = 2, Text = "Paste as Plain Text", Icon = SvgIcon.ClipboardText },
        new SplitButtonModel() { Id = 3, Text = "Paste as HTML", Icon = SvgIcon.ClipboardHtml },
    };

    private SplitButtonModel PrimaryButton { get; set; } = null!;

    private string SplitButtonLog { get; set; } = string.Empty;

    private void OnSplitButtonClick(SplitButtonModel button)
    {
        PrimaryButton = button;

        var now = DateTime.Now;
        SplitButtonLog = $"{button.Text} at {now.ToString("HH:mm:ss")}.{now.Millisecond}";
    }

    protected override void OnInitialized()
    {
        PrimaryButton = AllSplitButtons.First();
    }

    public class SplitButtonModel
    {
        public int Id { get; set; }
        public string Text { get; set; } = string.Empty;
        public object Icon { get; set; } = SvgIcon.Gear;
    }
}

See Also

In this article