What is attribute splatting, and how to use it in Blazor?
In Blazor WebAssembly, the @on{EVENT} attribute simplifies event handling. However, when dealing with components, it's often necessary to provide multiple attributes, but assigning values individually can be tedious. Attribute splatting makes this task easier for us.
Attribute splatting
Attribute splatting in Blazor WebAssembly offers a solution by allowing us to bypass the direct assignment of attributes in the HTML markup. It involves bundling all attributes in a dictionary and passing them as a single unit to the component. Each attribute is added as a dictionary entry, and the dictionary implements IEnumerable<KeyValuePair<string, object>> or IReadOnlyDictionary<string, object> with string keys. To reference the dictionary, we use the @attributes directive. The following image depicts the concept of using attribute splatting.
The image below depicts passing attributes using attribute splatting explicitly in the parent component.
Code example
In the following example, we create two child components. The first component uses the attribute splatting concept, while the other does not. Both components display buttons with the same characteristics.
<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="7.0.5" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="7.0.5" PrivateAssets="all" />
</ItemGroup>
</Project>
Code explanation
Lines 3–5: Call
Componentand pass a reference to theInputAttributedictionary using the@attributedirective.Lines 7–11: Call
Componentand pass each attribute explicitly.Lines 15–20: Define the
InputAttributedictionary with some properties.
The main advantage of using attribute spalling is to make the code reusable. Now, we can pass InputAttribute to another component for which we want the same properties.
Free Resources