Is there a way to extend a Blazor component to add custom properties?

440 Views Asked by At

I need to dynamically control whether a component is rendered to the page. I know I can just wrap things in an @if block, but I think adding an IsVisible property to an existing component would be cleaner.

Update

I'll rephrase the question and add some context.

My users want to select which fields are visible. I will show them a dialog where they can select which fields they want. Their preferences will be stored in a database. I was hoping to extend the component to control its visibility. I actually did create a wrapper component, but it has it seems hacky and not much better than a simple @if block. Here is a simple working example for toggling fields.

https://try.mudblazor.com/snippet/wOQRafwxfwppEuyo

1

There are 1 best solutions below

0
Brian Parker On

You can inherit a component they are just a C# class. To avoid the Razor compiler do not use the .razor extension.

SomeComponentExtended.cs

public class SomeComponentExtended : SurveyPrompt
{
    [Parameter]
    public bool IsVisible { get; set; }

    protected override void BuildRenderTree(RenderTreeBuilder builder)
    {
        if (IsVisible)
        {
            base.BuildRenderTree(builder);
        }
    }
}