Blazor templating component with inheritance - c#

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.

Related

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

Render Blazor child component with parameters

I'm new to Blazor and I'm currently working on a Blazor Webassembly .net 5.0 application.
I try to figure out the correct way to
render a child component
from a parent component
on button click (form submit)
pass parameters from the parent component to => the child component
My current solution seems to work, but unfortunately it ends in an infinite rendering loop: I use the OnParametersSetAsync method in the child component to handle the data loading.
Side note: I use Telerik Blazor components, but it should have no impact.
My parent component looks like this:
View (parent)
// I want to submit a form to set a bool = true, and then to rend the child component - is that ok?
<EditForm OnValidSubmit="#(async () => await StartEverything())">
<label for="OrderNumber">OrderNumber: </label>
<TelerikTextBox #bind-Value="OrderNumber" Id="OrderNumber" />
<TelerikButton ButtonType="#ButtonType.Submit">Start Everything</TelerikButton>
</EditForm>
#if (ShowChild)
{
<MyChildComponent OrderNumber="OrderNumber"/>
}
else
{
<div>Please enter an order number.</div>
}
Code Behind (parent)
public class MyParentComponent : ComponentBase {
protected int OrderNumber { get; set; }
protected bool ShowChild { get; set; }
protected async Task StartEverything()
{
if (OrderNumber > 0)
{
await Task.FromResult(ShowChild = true);
}
}
}
My child component looks like this:
View (child)
#if (Customer != null)
{
<p>#Customer.CustomerName</p>
<p>#Customer.AgencyName</p>
}
Code Behind (child)
public class MyChildComponent : ComponentBase {
// I need this Parameter sent from my parent component
[Parameter]
public int OrderNumber { get; set; }
protected CustomerViewModel Customer { get; set; }
protected override async Task OnParametersSetAsync()
{
var parameterForQuery = OrderNumber; // this should hold the value sent from the parent component
// Load Customer ViewModel Data here - is this the correct event? What is the best approach?
}
}
Item ViewModel
public class CustomerViewModel
{
public string CustomerName { get; set; }
public string AgencyName { get; set; }
}
Do you know how to correctly render a Child Component within a Parent Component and pass parameters from the Parent Component to the child component - then render the child component ONLY ON BUTTON CLICK (form submit, no infinite render loop)?
Do you know how to solve this problem?
I recommend going through https://blazor-university.com. It's the site that kind of got me kick-started when I first started with Blazor.
In regard to your question, I recommend the following:
https://blazor-university.com/components/component-lifecycles/
In particular, the following statement should prove useful in your case (from that link):
OnInitialized / OnInitializedAsync
This method is only executed once when the component is first created.
If the parent changes the component’s parameters at a later time, this
method is skipped.
It seems likely that simply changing which method you override will solve your problem, since OnParametersSetAsync behaves as you've described, and 'OnInitializedAsync' behaves as you want. :D

How to pass value from Child component (RenderFragment) to Parent page in C# Blazor?

I have a Blazor project that loads DLL that contain razor components. To render these dynamic components at client-side, I use render tree builder to create a RenderFragment from dynamic component and place it on the page to show the component. However, I can't find a way to bind a value while creating the render tree. Normally, I can pass data using the example below of parent and child component, but not sure how to do it when converting dynamic components to RenderFragment.
Parent component
#page "/ParentComponent"
<h1>Parent Component</h1>
<ChildComponent #bind-Password="_password" />
#code {
private string _password;
}
Child component
<h1>Child Component</h1>
Password:
<input #oninput="OnPasswordChanged"
required
type="#(_showPassword ? "text" : "password")"
value="#Password" />
<button class="btn btn-primary" #onclick="ToggleShowPassword">
Show password
</button>
#code {
private bool _showPassword;
[Parameter]
public string Password { get; set; }
[Parameter]
public EventCallback<string> PasswordChanged { get; set; }
private Task OnPasswordChanged(ChangeEventArgs e)
{
Password = e.Value.ToString();
return PasswordChanged.InvokeAsync(Password);
}
private void ToggleShowPassword()
{
_showPassword = !_showPassword;
}
}
Dynamic Component to RenderFragment
The code below shows how I am able to show the component on the page by converting it to RenderFragment. Do you know how I can bind a variable at the render tree builder, to pass data from dynamic component to the parent page?
Note: This Dynamic Component #dynamicComponent is same as the Child component above and I want the password data from it.
#page "/{ComponentName}"
#inject IComponentService ComponentService
#if (render)
{
#dynamicComponent()
#_password;
}
#code{
private string _password;
[Parameter]
public string ComponentName { get; set; }
bool render = false;
protected override void OnInitialized()
{
render = true;
base.OnInitialized();
}
RenderFragment dynamicComponent() => builder =>
{
RazorComponentModel component = ComponentService.GetComponentByPage(ComponentName);
builder.OpenComponent(0, component.Component);
for (int i = 0; i < component.Parameters.Count; i++)
{
var attribute = component.Parameters.ElementAt(i);
builder.AddAttribute(i + 1, attribute.Key, attribute.Value);
}
builder.CloseComponent();
};
}
Let us first see if I understood you right... You want to create a sort of component renderer, which gets a component's name as a parameter, and by means of the IComponentService you gets the component's Type, and then render it. I also guess that the component's Type may be Type Child, and you want to know how to render it in the Index page, and gets the password entered in the Child component, right ?
The following code describes how to do that, but of course I cannot use the IComponentService service to discover the type of the component, but instead assume that the type is Child.
Copy and run the code snippet. Test it... It should work...
#page "/{ComponentName?}"
#using Microsoft.AspNetCore.Components.CompilerServices;
#if (render)
{
#dynamicComponent
}
<p>Your password: #_password</p>
#code{
private string _password;
[Parameter]
public string ComponentName { get; set; }
bool render = false;
protected override void OnInitialized()
{
render = true;
base.OnInitialized();
}
RenderFragment dynamicComponent => builder =>
{
builder.OpenComponent(0, typeof(Child));
builder.AddAttribute(1, "Password", _password);
builder.AddAttribute(2, "PasswordChanged",
EventCallback.Factory.Create<string>(this,
RuntimeHelpers.CreateInferredEventCallback(this, __value => _password = __value, _password)));
builder.CloseComponent();
};
}
Note: You should not modify the values of the parameter properties in your Child component. Parameter properties in Blazor are auto properties, meaning that you can access their values but you must not change them.
Also, you shouldn't create sequence number by a loop. Sequence numbers should be hard-coded. Googlize this subject discussed in an article by Steve Anderson.

Blazor Two Way Binding Text Area inside component

I am trying to two-way bind a text area inside a child component in Blazor and I just can't figure it out.
Parent
#page "/test"
<h3>Parent Component</h3>
<input type="text" #bind="mydata" />
<TWBTextArea #bind-ChildData=#mydata></TWBTextArea>
#code {
public string mydata = "test";
}
Child
<h4>Child Component</h4>
<textarea #bind=#ChildData></textarea>
#code {
[Parameter] public string ChildData { get; set; }
[Parameter]
public EventCallback<string> ChildDataChanged { get; set; }
}
When I update from the parent component, the child textarea updates, but when I update the child text area, the parent is not updated.
Additional note : If I change the value being passed from a string to an object with a string property and I pass that object to the Child Component, two way binding DOES work but only after an update to the parent component.
Thanks in advance for any help!
Important: You should not bind to components' parameters as it may have side-effects on your app. Read this post by Steve Sanderson
Note that I define a local variable, named data, into which I assign the ChildData parameter property's value from the OnParametersSet method. That is done, as I've said before, in order to refrain from binding to a component's parameter.
Since we are creating a two-way data-binding, the value attribute of the textarea element is bound to the variable data. The flow of data is from the variable to the element. We also need to create an event handler, named here HandleOnChange, whose role is to update the local variable data, as well as to invoke the EventCallback 'delegate', passing the new value stored in the data variable. This value is gladly received in the parent component's mydata field, after which, a re-rendering occurs to reflect the new changes.
Note that I'm using the input event, instead of the change event, to make life easier and more interesting.
Child component
<h4>Child Component</h4>
<textarea #oninput="HandleOnChange">#data</textarea>
#code {
private string data;
[Parameter] public string ChildData { get; set; }
[Parameter]
public EventCallback<string> ChildDataChanged { get; set; }
private async Task HandleOnChange(ChangeEventArgs args)
{
data = args.Value.ToString();
await ChildDataChanged.InvokeAsync(data);
}
protected override void OnParametersSet()
{
data = ChildData;
base.OnParametersSet();
}
}
Usage
#page "/test"
<h3>Parent Component</h3>
<input type="text" #bind="mydata" #bind:event="oninput" />
<ChildComponent #bind-ChildData="mydata" />
#code {
private string mydata = "test";
}
I seem to have it working now by inheriting InputBase and binding to the CurrentValue property, but it was definitely something of an uphill battle.
#inherits InputBase<string>
<textarea class="#Class" #bind="CurrentValue"
#attributes="AdditionalAttributes" />
#code
{
[Parameter]
public string Id { get; set; }
[Parameter]
public string Class { get; set; }
protected override bool TryParseValueFromString(string value, out string result, out string validationErrorMessage)
{
result = value;
validationErrorMessage = null;
return true;
}
}

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 :)

Categories