Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor non-base class inheritance

Consider a simple blazor component MyText

<p>@Title</p>

public partial class MyText
{
    [Parameter] public string Title { get; set; }
}

In page I use it as: <MyText Title="Abc" />

Now I would like to extend this component but do not want to change it, rather derive it by a new component MyTextEx and add another parameter. Something like:

@inherits MyText

<!-- Show base component something like: --!>
@base

<p>@Message</p>

public partial class MyTextEx
{
    [Parameter] public string Message { get; set; }
}

What I could not find how to display the base component's content? So it is rendered as:

<p>@Title</p>
<p>@Message</p>

Note this is a simplified example and my base component has a lot of parameters, events and hoping for virtual methods which could be overridden by extended/derived component. I'm trying to avoid composition like approach in razor file for base component because AFAIK I have to again populate it with parameters:

@inherits MyText

<MyText Title="@Title" />

<p>@Message</p>

I was able to find inheritance examples with base/abstract components, but could not find inheritance with final components.

Any idea how to achieve this?

Thanks, Csaba

like image 925
Csaba Avatar asked Aug 28 '26 15:08

Csaba


2 Answers

@inherits MyText

<!-- Show base component like: --!>
@RenderBase()

<p>@Message</p>

@code 
{    
    // Message etc ...

    RenderFragment RenderBase() => builder => base.BuildRenderTree(builder);    
}
like image 145
Henk Holterman Avatar answered Aug 30 '26 05:08

Henk Holterman


A more direct alternative to the accepted answer:

@inherits MyText

<!-- Show base component something like: --!>
@{ base.BuildRenderTree(__builder); }

<p>@Message</p>

public partial class MyTextEx
{
    [Parameter] public string Message { get; set; }
}
like image 20
sw1337 Avatar answered Aug 30 '26 04:08

sw1337



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!