Skip to content
GitHub11 stars

Merges attributes the way the primitives do: event handlers chain, classes join and styles append.

Merging sets of attributes means handling event handlers, class and style. Here it's two helpers, one for each place you need it.

MergeProps

MergeProps.Merge merges sets of attributes. Later sets win, except that event handlers all run (the later set's first), class values are joined, and style declarations are appended, so the later set's win. Use it when a Render fragment needs a part's attributes and your own on one element:

<MenuItem>
    <Render Context="item">
        <a @attributes="MergeProps.Merge(item.Attributes, _link)">Settings</a>
    </Render>
</MenuItem>

@code {
    private readonly Dictionary<string, object> _link = new() { ["href"] = "/settings", ["class"] = "menu-link" };
}

AttributeBuilder

AttributeBuilder builds the attributes a part renders: the ones its author wrote (class, style, data-testid, handlers...) overlaid with the part's own. The part's values win, except that both event handlers run (the author's first), the author's style comes after the part's, and Default values apply only when the author didn't set one. A null value removes the attribute, and Flag renders a presence attribute such as data-open.

Here the button gets type="button" unless its author set a type, data-pressed="" only while it's pressed, and an onclick that runs after the author's.

protected override void BuildAttributes(AttributeBuilder attributes) => attributes
    .Default("type", "button")
    .Set("aria-pressed", Pressed ? "true" : "false")
    .Flag("data-pressed", Pressed)
    .Set("onclick", _onClick);

See Use Render for building a whole part with it.

API Reference

MergeProps

AttributeBuilder