Search code examples
blazor

basic component layout inheritance blazor


Let's say most of my components have a header. I want to create a base component that has the header variable and make all the other components inherit from that component and set the header. So I have

BaseComponent

@inherits LayoutComponentBase;

<h1>@header</h1>

@Body

@code {

    protected string header;
}

Component

@inherits BaseComponent;

"internal component text"

@code {
  protected override void OnInitialized()
    {
         base.header = "Setting header for the parent"
    }
}

This compiles and shows up with no errors but the base header doesn't show up. It's like anything in the base doesn't get rendered. What am I doing wrong?

P.S.

I have also tried @layout BaseComponent, and even both directives at the same time.


Solution

  • 2022 Update - This approach works fine for me in .NET 6.

    Base Component:

    <h1>@Header</h1>
    
    @code{
        public string? Header {get; set;}
    }
    

    Derived Component:

    @inherits BaseComponent
    
    @code {
        protected override void OnParametersSet()
        {
            base.Header = "New Header Value";
        }
    }