How can I style Blazor Components differently

Say I have Component <MyText />. How can I style it differently based on different places it is implemented?

For instance, this is what I would want to do (using bootstrap classes for ease):

MyDocument.razor

<div> This text below will be red.</div>
<MyText class="text-danger" /> 

<div> This text below will be blue.</div>
<MyText class="text-info" />

Which would output the following
enter image description here

1 answer

  • answered 2020-11-25 05:49 Brian Parker

    Take a look at Attribute splatting and arbitrary parameters
    MyText.razor

    <div @attributes="AdditionalAttributes">Some Cool Text</div>
    
    @code {
     [Parameter(CaptureUnmatchedValues = true)]
     public Dictionary<string, object> AdditionalAttributes { get; set; }
    }
    

    MyDocument.razor

    <div> This text below will be red.</div>
    <MyText class="text-danger" /> 
    
    <div> This text below will be blue.</div>
    <MyText class="text-info" />