Home > front end >  Blazor Wasm - How to update base components from an inherited component?
Blazor Wasm - How to update base components from an inherited component?

Time:11-16

I have a Blazor Wasm app with two components:

BaseComp.razor:

<h1>I'm base - @Text</h1>

@code{
    protected string Text {get; set;} = "Default";
}

ChildComponent.razor

@inherits BaseComp

<BaseComp/>

<h1>Hello, only child text!</h1>

@code {
    protected override void OnInitialized()
    {
        Text = "new";
    }
}

and on the page the following will be displayed:

I'm base - Default
Hello, only child text!

How could I update the Text property of the baseComponent from the childComponent?

CodePudding user response:

With this piece of code

@inherits BaseComp
<BaseComp/>  @* a new instance, not inheritance *@

You inherit from and compose with BaseComp. You are not using the inheritance part.

So use only composition and follow the answer from @MarvinKlein but remove the @inherits line. Or change the code to:

@inherits BaseComp

@*<BaseComp />*@
@{ base.BuildRenderTree(__builder); }

<h1>Hello, only child text!</h1>

CodePudding user response:

You'll need to declare it as a parameter and pass the value down.

BaseComp.razor:

<h1>I'm base - @Text</h1>

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

ChildComponent.razor

<BaseComp Text="Text"/>

<h1>Hello, only child text!</h1>

@code {
    protected override void OnInitialized()
    {
        Text = "new";
    }
}
  • Related