Modifiy Blazor Cascading Value between Child Components - c#

I'm new to Blazor and trying to work through some of the basics of how to construct my components and pages. Right now I have a MainLayout that looks like this:
<CascadingValue Value="#layoutVals" Name="LayoutVals">
<Leftbar />
<div class="content-page">
<Topbar />
<div class="content">
<div class="container-fluid">
#Body
</div>
</div>
</div>
</CascadingValue>
#code {
public LayoutValues layoutVals = new LayoutValues()
{
Title = "Dashboard",
Breadcrumbs = new Dictionary<string, string>()
{
{ "Dashboard", "/" }
}
};
}
I'm trying to use the cascading value to allow a child page/component to overwrite values in the Topbar component (i.e. page title, breadcrumb, some other display values that I want consistent across views but dynamically replaced based on the page).
I'm able to access the object in the Topbar component and they are set properly based on what they're initialized to in MainLayout (shown above), and I'm able to override them within that component. However, if I set them in a page the change doesn't seem to make it's way up and then back down the chain to the Topbar component where I want them displayed.
I'm sure I could eliminate the Topbar component and inline everything in my MainLayout but I'd prefer to keep the code clean and separate if it's possible.

The problem you are facing is, that the <Topbar /> is not re-rendered after the value has changed in some component down below the tree (page, etx). You have to tell the Topbar that to render again:
public class LayoutValues
{
public string Title {get;set;}
public Action ValuesChanged;
}
Subscribe to ValuesChanged in Topbar:
protected override void OnInitialized()
{
LayoutVals.ValuesChanged += () => StateHasChanged();
//dont forget to unsubscribe somewhere
}
[CascadingParameter] public LayoutValues LayoutVals {get;set;}
And call it whenever you change the value (or you can do this in setter of LayoutValues):
//some page
private void ButtonClicked()
{
LayoutVals.Title="Changed title";
LayoutVals.ValuesChanged.Invoke();
}
[CascadingParameter] public LayoutValues LayoutVals {get;set;}
Working demo.
This solution has a performance advantage - the app doesn't have to re-render the whole tree, just the Topbar has called the StateHasChanged.

Related

Inherit methods from component in Blazor

I have a modal component in Blazor that I am attempting to make more reusable. The modal has a base class which implements methods for Showing/Hiding the modal, and callbacks for Show and Hide.
public class Modalbase : ComponentBase
{
[Parameter] public RenderFragment ChildContent { get; set; }
[Parameter] public Action? Closed { get; set; }
[Parameter] public Action? Opened { get; set; }
protected bool show;
// ANCHOR - public methods
public void Hide()
{
show = false;
Closed?.Invoke();
this.StateHasChanged();
}
public void Show()
{
show = true;
Opened?.Invoke();
this.StateHasChanged();
}
}
For the razor implementation, I have a very simple component which provides the markup and renders content provided. This is in Modal.razor:
#inherits Modalbase
#if (this.show)
{
<div class='modal-container #(this.show ? "show" : "hidden")'>
<div class="overlay" #onclick="Hide" style="cursor:pointer;"></div>
<div class='modal'>
<div id="close-container" #onclick="Hide">
<div class="close"><i class="fa-solid fa-x fa-md"></i></div>
</div>
#this.ChildContent
</div>
</div>
}
which is then used like this:
<Modal #ref="modalRef">
<div>childcontent here</div>
</Modal>
#code {
Modal modalRef;
public void Show()
{
modalRef.Show();
}
}
The problem with this is that across many implementations of Modals, I have to keep implementing the Show and Hide methods. Those methods are on the Modal component reference, and not in the reference to the implementation of Modal.
Is there a way with OOP to have these methods available directly on the implementation of the Modal component, but also allow them to be overriden if something additional needs to be done before opening/closing the modal?
A workaround is just making modalRef public in implementations, and calling the methods directly from there. Like: childModal.modalRef.Show() But that feels like it could cause issues in cases where maybe I want to check if the user is logged in before showing the modal.

Blazor templating component with inheritance

I have a base component PetTemplate and a second PetDog that inherits and uses the template of PetTemplate. PetTemplate has a method named ToggleDisplay. My goal is when I click the button on the Index page that invokes the PetDog.ToggleDisplay method and show/hide the PetDog details on the page.
The "Inside" button in the sample code below works but "Outside" button don't. How can I invoke the ToggleDisplay method from a page or a parent component correctly?
Index.razor
#page "/"
<button #onclick="ShowPetDetails">Show Details (Outside)</button>
<PetDog #ref="dog" />
#code {
PetDog dog;
void ShowPetDetails()
{
dog.ToggleDisplay();
}
}
PetDog.razor
#inherits PetTemplate
<PetTemplate Name="Dog">
<div>Someone's best friend!</div>
</PetTemplate>
PetTemplate.razor
<div class="mt-3">
<button #onclick="ToggleDisplay">Show Details (Inside)</button>
<h3>Pet Name: #Name</h3>
<div style="display:#display">
#ChildContent
</div>
</div>
#code {
string display = "none";
[Parameter]
public string Name { get; set; }
[Parameter]
public RenderFragment ChildContent { get; set; }
public void ToggleDisplay()
{
display = display == "none" ? "block" : "none";
StateHasChanged();
}
}
When you use
<PetDog #ref="dog" />
#code {
PetDog dog;
void ShowPetDetails()
{
dog.ToggleDisplay();
}
}
You actually create a reference to the PetDog component, and then try to call a derived method, dog.ToggleDisplay(), on object you have no reference to ( the instance of the PetTemplate). In order to make it work, you'll have to get a reference to the parent component (PetTemplate), and provide it to the derived component (PetDog), like this:
PetTemplate.razor
<div class="mt-3">
<button #onclick="ToggleDisplay">Show Details (Inside)</button>
<h3>Pet Name: #Name</h3>
<div style="display:#display">
#ChildContent
</div>
</div>
#code {
string display = "none";
string val;
[Parameter]
public string Name { get; set; }
[Parameter]
public RenderFragment ChildContent { get; set; }
public void ToggleDisplay()
{
display = display == "none" ? "block" : "none";
InvokeAsync(() => StateHasChanged());
}
}
PetDog.razor
#inherits PetTemplate
<PetTemplate #ref="petTemplate" Name="Dog">
<div>Someone's best friend!</div>
</PetTemplate>
#code
{
PetTemplate petTemplate;
public PetTemplate PetTemplateProp { get; set; }
protected override void OnAfterRender(bool firstRender)
{
if(firstRender)
{
PetTemplateProp = petTemplate;
}
base.OnAfterRender(firstRender);
}
}
Index.razor
#page "/"
<button #onclick="ShowPetDetails">Show Details (Outside)</button>
<PetDog #ref="dog" />
#code {
PetDog dog;
void ShowPetDetails()
{
dog.PetTemplateProp.ToggleDisplay();
}
}
Note: Though Razor components are C# classes, you cannot treat them as normal classes. They behave differently. As for instance, you can't define a variable instance, and set its parameters, etc. outside of the component. At best, you can capture a reference to a component as well as call public methods on the component instance, as is done in the current sample. In short, component objects differ from normal classes.
It's also important to remember that each component is a separate island that can render independently of its parents and children.
But just wondering how can I change a component parameter value from outside of it, that inherited/uses a template. I tried the methods in the documentation or the resources I found, but it didn't work for my case
You should not (it was a warning) and probably cannot ( it may be now an error) change a component parameter's value outside of the component. As for instance, you can't capture a reference to a component and assign a value to its parameter property:
<PetTemplate #ref="petTemplate">
<div>Someone's best friend!</div>
</PetTemplate>
PetTemplate petTemplate;
This is not allowed: petTemplate.Name="Dog" as this is changing the parameter outside of its component. You can only do that like this:
<PetTemplate Name="Dog">
<div>Someone's best friend!</div>
</PetTemplate>
Furthermore, modification of a parameter property from within the component itself is deprecated ( currently you should get a warning, at least that is what Steve Sanderson suggested to the Blazor team).
To make it clear, you should not modify the parameter property Name from within the PetTemplate component. A parameter property should be automatic property; that is, having a get and set accessors like this: [Parameter] public string Name { get; set; }
And you should not use it like this:
private string name;
[Parameter]
public string Name
{
get => name;
set
{
if (name != value)
{
name = value;
// Code to a method or whatever to do something
}
}
}
This is deprecated as it may have side effects. Component parameters should be treated as DTO, and should not be modified. If you wish to perform some manipulation of the parameter value, then copy it to a local variable, and do your thing.
As pointed out by #enet Blazor component inheritance doesn't behave exactly as one would intuitively expect. This is a cleaner approach when you want to control a UI functionality that can be controlled both internally and externally:
Declare an event in the base component that is raised when the UI state is changed from within the component. Also let the variable that controls the state be a parameter. In you case, something like
PetTemplate.razor:
[Parameter]
public EventCallback OnToggleRequested {get;set;}
[Parameter]
public string Display {get;set;}
protected async Task RaiseToggle()
{
await OnToggleRequested.InvokeAsync();
}
In your PetDog, simple call the toggle method when inside click is raised
PetDog.razor:
<button #onclick="RaiseToggle">Show Details (Inside)</button>
In your container (in this case, index.razor) listen to the event and make changes. Also wire the outside button to the same method:
Index.razor:
<button #onclick="ToggleDisplay">Show Details (Outside)</button>
<PetDog OnToggleRequested="ToggleDisplay" Display="#display"/>
string display = "block";
void ToggleDisplay()
{
display = display == "none" ? "block" : "none";
}
Note that the event can be used at level of hierarchy and you don't need to capture any references anywhere.

How does Blazor handle sharing data among multiple components and nested components?

I have a Blazor app with many components, and nested components that I would like to share data among, but I cannot figure out how to do this efficiently. Here is, sort of, what I have:
MyProject.Pages.Index.razor:
#page "/"
<div>
#if(some_state) {
<ComponentAlpha #bind-something=Something />
else if(some_other_state){
<ComponentBeta Something="Something" />
} else {
<ComponentGamma Something="Something" />
}
</div>
#code {
String Something { get; set; }
}
MyProject.Shared.ComponentAlpha.razor:
<div>
Stuff here ...
</div>
#code {
[Parameter]
public String something { get; set; }
[Parameter]
public EventCallback<String> somethingChanged { get; set; }
private async Task MyTask() {
await somethingChanged.InvokeAsync(something);
}
}
This all works fantastic for getting data from ComponentAlpha.razor back to Index.razor, and from Index.razor to ComponentBeta.razor and ComponentGamma.razor. My question comes in for beyond ComponentBeta.razor and ComponentGamma.razor.
MyProject.Shared.ComponentBeta.razor:
<div>
Stuff here ...
<ComponentDelta />
<ComponentEpsilon />
</div>
#code {
[Parameter]
public String Something { get; set; }
}
MyProject.Shared.ComponentGamma.razor:
<div>
Stuff here ...
<ComponentZeta />
<ComponentEta />
</div>
#code {
[Parameter]
public String Something { get; set; }
}
MyProject.Shared.ComponentDelta.razor:
MyProject.Shared.ComponentEpsilon.razor:
MyProject.Shared.ComponentZeta.razor:
MyProject.Shared.ComponentEta.razor:
<div>
Stuff here ...
<MoreAndMoreComponents />
</div>
#code {
// I want to use variable "something" here as well.
}
In order to be able to share the string something amongst all my components and embedded components, do I need to jump through all the elaborate hoops that I did for just Index.razor, ComponentAlpha.razor, and ComponentBeta.razor or is there some better way?
I saw THIS out there and thought option 3. State Container would be my best bet, However, when I follow their example, I always end up with this Exception:
Error CS0119 'AppState' is a type, which is not valid in the given context
So, what is the way we are supposed to use to efficiently share data amongst all components and nested components?
You should consider using a service, probably Scoped. You then inject the service into each component, you can use an Interface and/or base abstract class to boilerplate the code. You can also use this same service for events - signalling that data has changed.
See the MS Docs here on services and how to use/provision them.
One option you can consider is using cascading parameters, which will allow a top level component to pass itself down to any child components regardless of component tree depth. It's very easy to set up.
In your top level component:
<CascadingValue Value="this">
#*Note Component Alpha placement*#
<ComponentAlpha />
</CascadingValue>
#code {
private string something = "initial value";
// this is a getter only for the property, but you can use
// a setter for 2 way binding also. Just make sure
// to modify the setter to run 'StateHasChanged()'
// after updating the value, and then
// you can then set the property directly
public string Something => something;
// This will allow child components to set the new value
public Task SetNewValue(string value)
{
something = value;
StateHasChanged();
return Task.CompletedTask;
}
}
Note that the CascadingValue is passing this down the tree to it's children, so you can capture it where needed.
In the mid level (alpha) component
<div>
<div #onclick="SetNewValue">#ValueFromTopLevel</div>
#*Note Component Beta placement*#
<ComponentBeta />
</div>
#code {
// Capture the top level component here
[CascadingParameter]
public Component TopLevelComponent { get; set; }
// pull out the value you need here
public string ValueFromTopLevel => TopLevelComponent.Something;
// use this to set a new value
void SetNewValue()
{
TopLevelComponent.SetNewValue("Hello from Alpha component!");
}
}
Notice the beta component nested inside the alpha component.
In the low level (beta for my example) component
<div>
<div #onclick="SetNewValue">#ValueFromTopLevel</div>
</div>
#code {
// still capture the top level component
[CascadingParameter]
public Component TopLevelComponent { get; set; }
// use the value the same as Alpha
public string ValueFromTopLevel => TopLevelComponent.Something;
// set the value the same as Alpha
void SetNewValue()
{
TopLevelComponent.SetNewValue("Hello from Beta component!");
}
}
With this setup, by clicking on the text of either the Alpha or the Beta component, the value of something is updated at the top level and then the new value is cascaded down again with a fresh render. All the state management is at the top and the child components are just hooking in where needed.This setup will allow you to use methods and properties from a top level component as you see fit. For example I created a top level Toast Notification component once that wraps the whole app and can be captured and used anywhere. Simply pass it a message and a type (info, error, warning) and it displays the flash message for a few seconds and then hides again.
There are some downsides though, notably that your top level component needs to be responsible for all state management. This works for simpler scenarios, but as the app and the interactions become more complex this can get out of hand. However, if you combine this with Enet's answer and get the state management happening at the top, you can then hook in where needed down the component tree.
Also note that any child components become coupled to the top level parent as they will require being up the tree somewhere to work properly. Maybe Ok for you, maybe not. Either way, it's a good tool to be aware of.
Official docs for cascading parameters can be found here
It depends how permanent you need your info to be, and to what degree you're willing to hold global variables on the parent.
1. One trick is to pass the parent control to the children-- give them full access to its variables:
ParentControl
<CascadingValue Value="this">
<ChildControl />
</CascadingValue>
ChildControl
[Parameter]
ParentControl Parent;
#code {
Parent.SomeVariable = Something;
}
2. If you don't want to do that, then you can pass data to its parent using an EventCallback<T>
ChildControl
#code
{
[Parameter]
EventCallBack<MyCustomClass> OnDataReady { get; set; }
MyCustomClass ActiveObject { get; set; }
void DoSomething()
{
OnDataReady.InvokeAsync(ActiveObject);
}
}
And on ParentControl:
<ChildControl OnDataReady=HandleData />
#code {
async Task HandleData (MyCustomClass data){
// Do stuff
}
}
3. If you REALLY want highly persistent data, then consider saving state in a database. Since Blazor requires no postbacks, there's really no penalty for saving or loading information from a database whenever you want.
4. Using a service as per #enet's answer

Is there an easy way to signal changes to data happening in child component?

Let's say I have a collection of data in my page loaded via OnInitializedAsync(). The data is shown graphically in a table but later on also in more detail in another table further down on the page.
Since the rows in the detailed table has a lot of controls and logic I decided to make a component for the row e.g. <RowData Data="#rowdata" /> and bound each row data.
The problem is that if the data gets changed in my child controller (RowData) it won't reflect in my first table in the "parent" component where the same data is also listed.
Is there an easy way to signal change or should I avoid making child components?
I have sovled it by making an EventCallback in my child component and updating via callback in my parent component. But I have the feeling I'm missing something.
The following sample shows how to perform two-way data-binding between a parent
component and its child component. In each of these two component is a text box controls. When you type text in the parent component's text box, the text in the child component's text box changes to reflect the changes made in the parent,
and vice versa...
ChildComponent.razor
<div style="border:solid 1px red">
<h2>Child Component</h2>
<input type="text" #bind="Text" #bind:event="oninput" />
</div>
#code {
private string text { get; set; }
[Parameter]
public string Text
{
get { return text; }
set
{
if (text != value) {
text = value;
if (TextChanged.HasDelegate)
{
TextChanged.InvokeAsync(value);
}
}
}
}
[Parameter]
public EventCallback<string> TextChanged { get; set; }
}
ParentComponent.razor
#page "/ParentComponent"
<h1>Parent Component</h1>
<input type="text" #bind="Text" #bind:event="oninput" />
<p></p>
<ChildComponent #bind-Text="Text" />
#code {
[Parameter]
public string Text { get; set; } = "Hello Blazor";
}
I have sovled it by making an EventHandler in my child component and updating via callback. But I have the feeling I'm missing something
What you've been missing is the existence of the EventCallback 'delegate' used in this sample to call the parent component and pass it the value entered in the child component. This is how we define the 'delegate'
[Parameter]
public EventCallback<string> TextChanged { get; set; }
And this is how we invoke it, when the value of the Text property changes:
TextChanged.InvokeAsync(value);
What delegate did you use ? Note that the EventCallback's target is not the child component, but the parent component...
Good luck... If something is not clear, don't hesitate to ask...
If you have a root component with N levels of nested components (children within children ad-nauseam) then you can use a cascading value. Try something like this
public class MyState
{
public List<MyObject> Objects { get; set; }
public Action OnModified { get; }
public MyState(List<MyObject> objects, Action onModified)
{
Objects = objects;
OnModified = onModified;
}
}
In your parent component
MyState State;
protected override OnInitialized()
{
State = new MyState(your objects, () => InvokeAsync(StateHasChanged));
}
In your parent markup
<CascadingValue Value=State>
All your child content here
</CascadingValue>
In your various child components that need access
[CascadingParameter]
public MyState State { get; set; }
protected void SomeEditWasMade()
{
State.Objects[23].Name = "Bob";
State.OnModified();
}
That should call the () => InvokeAsync(StateHasChanged) in the parent, and then that component and every component that consumes the MyState cascading value will get rerendered.
Or you could use something like Fluxor :)

Blazor components and linkage

Just hoping to get some help with some of this Blazor functionality. I'm building a true SPA app with no navigation, which means I'm going to need a fair bit of linkage.
Im going to follow some fundamentals of say Winforms or UWP were you have access to controls. And treat Blazor components as if they were controls. Do as much work in C# as I can.
So far I know:
For a child component, I can create an event callback, and register to it in the parent.
I can store a reference to the child component with the #ref tag. Then access functions of the child component after OnRender has been completed.
I can dynamically build a component using the builder.
But how do I pass a reference of the parent to the child? Like set a parameter of the child and pass "this".
The idea is that every child component of Index has a reference to the Index component. And the Index component has a reference to every child of Index.
So that way I can do things like when I click a button in the Header component.
I can call parent.PopupComponent.Show("Title");
I know it can be achieved with callbacks, but I would like to be able to make any call I need, access any variable etc. Through the linkage of components. Without needing to set up an extra callback function for each step.
Thank you in advance :)
You can pass a reference to the parent component to a child component as a regular parameter, as for instance:
Child.razor
#code {
[Parameter]
public Parent Parent { get; set; }
}
Parent.razor
#* Passing a parent reference to the child component*#
<Child Parent="this" />
#code {
}
You can also pass a CascadingParameter to child components. This is useful when you want to pass a reference to the parent component to all the children, as for instance:
Child.razor
#code {
[CascadingParameter]
public Parent Parent { get; set; }
[Parameter]
public RenderFragment ChildContent { get; set; }
}
Parent.razor
#* Passing a parent reference to the child components in the form of
CascadingValue*#
<CascadingValue Value=this>
#ChildContent
</CascadingValue>
#code {
}
And this is bonus:
The following code snippet illustrate how to add a child component to a parent component, from which you can call properties of the child component :
protected override void OnInitialized()
{
Parent.AddChild(this);
}
Note: The OnInitialized method is implemented on the child component, right ?
And the word this refers to the current object; that is the child component, right ?
Hope this helps...
I just wanted to add this in as some people may find it useful when trying to build a Blazor app the same way I am.
Here is how I found a way to control what content is being loaded into a component, in my case I made an empty Flyout/Window component, with the content set as a render fragment. Note that the render fragment is private, the is because the content will be a BlazorComponent, defined in the ShowPopup() call.
Also worth noting that the component builder stuff will most likely become obsolete as they build on Blazor. This is low-level API, and as mentioned by the Developers. They will have something more useful in the future.
Child Component Code
<div>
...
#childContent
</div>
#code
{
private RenderFragment childContent { get; set; }
public void ShowPopup(Type ComponentType)
{
childContent = CreateDynamicComponent(ComponentType);
//Show popup logic....
}
RenderFragment CreateDynamicComponent(Type T) => builder =>
{
builder.OpenComponent(0, T);
builder.CloseComponent();
};
}
Then the parent Code
<div>
...
<button #onclick="#(e => PopupWindow.ShowPopup(typeof(BlazorComponentX)))">Load BlazorComponentX into Popup</button>
<PopupWindow #ref="PopupWindow"></PopupWindow>
...
</div>
#code
{
Public PopupWindow PopupWindow {get; set;}
}

Categories