Make Your Blazor Components More Flexible With CaptureUnmatchedValues
Table of contents
No headings in the article.
You may have noticed when creating your Blazor components that if you try to use an attribute that you don't have a parameter for it fails to build. It can be annoying to have to add attributes for every little thing. That's where CaptureUnmatchedValues comes in.
To handle unexpected attributes we add a parameter to our component of type Dictionary<string, object>
. We also need modify the Parameter
attribute on the property: [Parameter(CaptureUnmatchedValues = true)]
.
Let's take a simple Button component and add a new parameter:
// Button.razor
<button class="btn btn-primary" @onclick="OnClick" @attributes="Attributes">
@Text
</button>
@code {
[Parameter]
public string Text { get; set; } = "Click me";
[Parameter]
public EventCallback OnClick { get; set; }
[Parameter(CaptureUnmatchedValues = true)]
public Dictionary<string, object> Attributes { get; set; }
}
Now when we go to use the Button we can add attributes that we aren't already handling and they'll work just fine:
<Button OnClick="IncrementCount" class="btn btn-primary" title="Button" />
// Renders as:
// <button class="btn btn-primary" title="Button">Click me</button>
I hope you found this helpful! Happy coding!