Skip to content

[Feature Request] Merging splatted attributes in Blazor #45230

@lonix1

Description

@lonix1

Is there an existing issue for this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe the problem.

Very often I have to do this:

<MyComponent class="foo bar baz" />

But that custom component also defines a class attribute with its own classes. So I need to jump through some hoops to merge them.

This happens enough times in custom components, that I put the common stuff in a base class, as I wrote on SO, here. That SO post has 12k views, so this is something people struggle with.

Describe the solution you'd like

I do something like this:

ChildComponent.razor

<div @attributes=_additionalAttributes></div>

@code {

  [Parameter(CaptureUnmatchedValues = true)]
  public IReadOnlyDictionary<string, object> AdditionalAttributes { get; set; }
    = new Dictionary<string, object>();

  private IReadOnlyDictionary<string, object>? _additionalAttributes;

  protected override void OnParametersSet()
  {
    base.OnParametersSet();

    var parentClasses = AdditionalAttributes.GetValueOrDefault("class", "");
    var classes       = $"foo {parentClasses}".Trim();

    _additionalAttributes = 
      AdditionalAttributes.Where(x => x.Key != "class")
      .Append(KeyValuePair.Create("class", (object)classes))
      .ToDictionary(x => x.Key, x => x.Value);
  }

}

ParentComponent.razor is now clean, with the normal name class:

<ChildComponent class="bar baz" />

@code {
}

Which renders:

<div class="foo bar baz"></div>

It would be nice if all that were built in. Maybe it could be:

Parameter(CaptureUnmatchedValues = true, MergeAttributes = true)]            // <--- note MergeAttributes
public IReadOnlyDictionary<string, object> AdditionalAttributes { get; set; }
  = new Dictionary<string, object>();

...and we could use that during attribute splatting.

Additional context

No.

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-blazorIncludes: Blazor, Razor ComponentsenhancementThis issue represents an ask for new feature or an enhancement to an existing one

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions