Setting CSS class on @ChildContent in Blazor Component

Viewed 1676

is there a way to set a css class on a child component inside a Blazor component?

What i have right now is:

@using Microsoft.AspNetCore.Components;
@inherits ComponentBase

<div class="button-group-wrapper">
    @SecondaryButton
    <div class="floating-sticky-wrapper">
        @PrimaryButton
    </div>
</div>

@code {
    [Parameter]
    public RenderFragment PrimaryButton { get; set; }

    [Parameter]
    public RenderFragment SecondaryButton { get; set; }
}

I then "inject" the RenderFragments via:

<FloatingStickyButton>
    <SecondaryButton>
        <button type="button" class="button ...">Secondary</button>
    </SecondaryButton>
    <PrimaryButton>
        <button type="submit" class="button button--primary ...">Primary</button>
    </PrimaryButton>
</FloatingStickyButton>

What do i want?

I want to set the css class called "floating-sticky-button" on the primary button. But i would like to set this css class inside the component so that the programmer does not need to care about setting the class outside on the button element.

Something like this (Mind the @PrimaryButton here):

@using Microsoft.AspNetCore.Components;
@inherits ComponentBase

<div class="button-group-wrapper">
    @SecondaryButton
    <div class="floating-sticky-wrapper">
        @PrimaryButton({class: 'floating-sticky-button'})
    </div>
</div>

@code {
    [Parameter]
    public RenderFragment PrimaryButton { get; set; }

    [Parameter]
    public RenderFragment SecondaryButton { get; set; }
}

Unfortunately that doesn't work. Is there any way to do this?

3 Answers

Here is an idea: Blazor - How to create Components dynamically

The problem with this solution is that you can only create a child component from a user-specified type (does not work with a RenderFragment) and then you can only completely override the class property.

Unfortunately, I'm afraid you need use javascript. A function like

var addClass = () => {
    let button = document.getElementsByClassName('button--primary');
    if (button && button[0] && button[0].classList)
        button[0].classList.add("floating-sticky-button");
}

And (in your component)

protected override async void OnAfterRender(bool firstRender)
{
    if (firstRender)
       await jsRuntime.InvokeVoidAsync("addClass");

    base.OnAfterRender(firstRender);
}

make the ugly trick

Related