-
Notifications
You must be signed in to change notification settings - Fork 25
StyleBuilder.AddStyleFromAttributes Method
Adds a conditional in-line style when it exists in a dictionary to the builder with space separator.
Null safe operation checks for the the style
dictionary key internally.
public StyleBuilder AddStyleFromAttributes(IReadOnlyDictionary<string, object> additionalAttributes)
If you encounter dynamic values due to attribute splatting, we can easily handle this as well.
Consider the senario where we need to merge a splatted style
attribute while preserving default values.
<!-- API -->
<MyComponent style="width:100">
<!-- Output -->
<div style="width:100%">
<div @attributes="AdditionalAttributes" style="@Style">
@code {
[Parameter(CaptureUnmatchedValues = true)]
public IReadOnlyDictionary<string, object> AdditionalAttributes { get; set; } = new Dictionary<string, Object>();
StyleBuilder Style => StyleBuilder().Empty().AddStyleFromAttributes(attributes);
}
When using dynamic attributes may result in empty attribute. When Blazor renders an attribute that has an empty string value, it will result in an empty attribute tag. However, if the value is null the attribute will be excluded. When an empty attribute is expected, the extension method NullIfEmpty can be used to clean up the resulting markup. Note: This method is only necessary when no default value is supplied. Ex: new StyleBuilder() or StyleBuilder().Empty(). Forgetting to call NullIfEmpty should not have any impact on the UI.
<!-- Output with Empty String -->
<div class="">
<!-- Output with null -->
<div>
<div class="@Style">
@code {
//string Style => StyleBuilder().Empty().AddStyleFromAttributes(attributes).Build();
string Style => StyleBuilder().Empty().AddStyleFromAttributes(attributes).NullIfEmpty();
}