Skip to content

Allow to inherit rendertree markup in blazor components #62233

Closed
@MarvinKlein1508

Description

@MarvinKlein1508

Is there an existing issue for this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe the problem.

I have some components which contains some public/proteced properties and methods and renders some basic UI based on them.

Take a look on this minimalistic card example:

<div class="card">
    @Text
</div>

@code {
    [Parameter]
    public virtual string Text { get; set; } = "MyCard";
}

The card defines a property Text which is set to MyCard by default. I can use this component now in two ways:

<MyCard /> <!-- Renders MyCard -->
<MyCard Text="Hello World" /> <!-- Renders Hello World -->

Now lets say I want to change the default value for this property using a custom component. So I create a new component and inherit from MyCard like this:

@inherits MyCard

@code {
    public override string Text { get; set; } = "InheritedMyCard";
}

Using this component now results in nothing because the rendertree from the base component is missing. In my case I want the UI to be exactly the same as before.

Right now I need to implement either <MyCard Text="@Text" /> (which requires a lot of work when you want many parameters supported) or I have to copy and paste the rendertree from the MyCard component (which isn't ideal if you work with third party component libraries which could change at any time) or I can create a protected renderfragment which I can call in my sub component:

public class MyCardCodeBehind : ComponentBase
{
    [Parameter]
    public virtual string Text { get; set; } = "MyCardCodeBehind";

    protected override void BuildRenderTree(RenderTreeBuilder builder) => RenderContent(builder);

    protected void RenderContent(RenderTreeBuilder builder)
    {
        builder.OpenElement(0, "div");
        builder.AddAttribute(1, "class", "card");
        builder.AddContent(2, Text);
        builder.CloseElement();
    }
}

Sadly though you will lose html syntax hightlighting here and it'S quite hard to setup and maintain for larger components and you cannot use scoped css for code-behind components only.

Describe the solution you'd like

I would like to be able to get the base rendertree somehow. So I can get the full rendering of the base component. This would also allow me to add stuff before and after the component in my sub component as well as overwriting properties and methods from my base component.

Maybe something like @base.RenderedHTML()

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions