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;
}
}
Related
I'm developing a UI library on top of Blazor and I like to enable the bind* syntax for my components so consumers could use it too.
Context
I've read and seen plenty of examples so on the most basic level let's say we have the following custom component named RawCustomInput.razor:
<input type="text" value="#Value" #onchange="OnValueChanged" style="width: 5rem" />
#code {
[Parameter]
public string? Value { get; set; }
[Parameter]
public EventCallback<string> ValueChanged { get; set; }
private async Task OnValueChanged(ChangeEventArgs args)
=> await ValueChanged.InvokeAsync(args.Value as string);
}
And another component that consumes it named InputPage.razor like this:
#page "/input"
<PageTitle>InputPage</PageTitle>
<RawCustomInput
#bind-Value="#_name" />
#if (!string.IsNullOrEmpty(_name))
{
<p>#_name</p>
}
#code {
private string? _name = null;
}
Problem
Now, the above works but say I want to change the event from onchange to oninput on the consumer side? so I tried to do something like this #bind-Value:event="oninput" but then I get the following error:
does not have a property matching the name 'oninput'
So I thought I could solve this by introducing #oninput="OnValueChanged" to RawCustomInput.razor which looks like this:
<input type="text" value="#Value" #onchange="OnValueChanged" #oninput="OnValueChanged" style="width: 5rem" />
#code {
[Parameter]
public string? Value { get; set; }
[Parameter]
public EventCallback<string> ValueChanged { get; set; }
private async Task OnValueChanged(ChangeEventArgs args)
=> await ValueChanged.InvokeAsync(args.Value as string);
}
But this didn't work so I read the error again and realized that something like #bind-Value:event="ValueChanged" might work and it worked! so what I did is add another property that looks like this:
[Parameter]
public EventCallback<string> ValueChanging { get; set; }
So now my RawCustomInput.razor looks like this:
<input type="text" value="#Value" #onchange="OnChange" #oninput="OnInput" style="width: 5rem" />
#code {
[Parameter]
public string? Value { get; set; }
[Parameter]
public EventCallback<string> ValueChanged { get; set; }
[Parameter]
public EventCallback<string> ValueChanging { get; set; }
private async Task OnChange(ChangeEventArgs args)
=> await ValueChanged.InvokeAsync(args.Value as string);
private async Task OnInput(ChangeEventArgs args)
=> await ValueChanging.InvokeAsync(args.Value as string);
}
And finally I could use the syntax below that worked too which is great but raises few questions.
<RawCustomInput
#bind-Value="#_name"
#bind-Value:event="ValueChanging" />
Questions
It's possible to use the syntax bind-{Property}="{Expression}" for binding but is it possible to enable this syntax bind="{Expression}" on custom components? because when I'm trying to do something like this <RawCustomInput #bind="#_name" /> it throws with the following error does not have a property matching the name '#bind' but this <input type="text" #bind="#_name" /> works, why?
It's possible to do <input type="text" #bind="#_name" #bind:event="oninput" /> but doing <RawCustomInput #bind-Value="#_name" #bind-Value:event="oninput" /> throws with the following error does not have a property matching the name 'oninput', why? to achieve a similar thing I have to introduce additional property as I pointed above but then it's seems a bit odd that for bind:event I need to provide the name of the event whereas for bind-{Property}:event I need to pass a property which might makes sense but I'm not sure I understand the reason.
First you need to understand the difference between components and elements.
<input type="text" value="#Value" .. is an element declaration. It's html code.
<RawCustomInput #bind-Value="#_name" /> is a component declaration.
Second, you are defining stuff in the Razor language, not true C#. #bind and #bind-value are directives to the Razor compiler, and are handled differently.
The #bind is used to bind elements. It gets compiled by the Razor compiler into C# code like this:
__builder.AddAttribute(19, "value", BindConverter.FormatValue(this.surName));
__builder.AddAttribute(20, "onchange", EventCallback.Factory.CreateBinder(this, __value => this.surName = __value, this.surName));
Note that it uses various factory classes to build the "getter" to provide a correctly formatted string to the input value and a "setter" to handle the generated onchange event from the input to update the variable.
In comparison, this is the code for the component #bind-value on a component
__builder.AddAttribute(11, "Value", RuntimeHelpers.TypeCheck<String>(this.firstName));
__builder.AddAttribute(12, "ValueChanged", RuntimeHelpers.TypeCheck<EventCallback<String>>(EventCallback.Factory.Create<String>(this, RuntimeHelpers.CreateInferredEventCallback(this, __value => this.firstName = __value, this.firstName))));
It's setting the value of the Parameter Value and creating an anonymous function to set the value from the eventcallback ValueChanged. There is no direct wiring into the underlying input element declared within the component. It's setting the component parameter and sinking the component event. How they are wired up is up to you the designer.
To demonstrate, here's a very different component wiring for a "checkbox":
<button class="#this.ButtonCss" #onclick=this.OnValueChanged>#this.ButtonText</button>
#code {
[Parameter] public bool Value { get; set; }
[Parameter] public EventCallback<bool> ValueChanged { get; set; }
private string ButtonCss => Value ? "btn btn-success": "btn btn-danger";
private string ButtonText => Value ? "Enabled" : "Disabled";
private async Task OnValueChanged()
=> await ValueChanged.InvokeAsync(!this.Value);
}
When you declare your components as Razor Components you are restricted by the Razor language. For 99% of components this is Ok. But, if you want to do more exotic stuff, you need to drop back to writing your component directly as a C# class.
This shows one way of handling onchange/oninput.
#if(this.ChangeOnInput)
{
<input type="text" value="#Value" #oninput="OnValueChanged" class="form-control" />
}
else
{
<input type="text" value="#Value" #onchange="OnValueChanged" class="form-control" />
}
#code {
[Parameter] public string? Value { get; set; }
[Parameter] public bool ChangeOnInput { get; set; }
[Parameter] public EventCallback<string> ValueChanged { get; set; }
private async Task OnValueChanged(ChangeEventArgs args)
=> await ValueChanged.InvokeAsync(args.Value as string);
}
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.
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.
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 :)
I'm playing around with the custom template in Blazor and I'm trying to find to a way to two-way bind a CascadingValue or achieve something similar. Right now I have the following template.
#if (PopupVisible)
{
<DxPopup>
<HeaderTemplate>
<h4 class="modal-title">#HeaderText</h4>
<button type="button" class="close" #onclick="#UpdatePopupVisible">×</button>
</HeaderTemplate>
<ChildContent>
<div class="modal-body">
<div class="container-fluid">
#bodyContent
</div>
</div>
<div class="modal-footer">
#footerContent
<button class="btn btn-secondary" #onclick="UpdatePopupVisible">Cancel</button>
</div>
</ChildContent>
</DxPopup>
}
#code {
[CascadingParameter] public bool PopupVisible { get; set; }
[CascadingParameter] public EventCallback<bool> PopupVisibleChanged { get; set; }
[Parameter] public RenderFragment HeaderText { get; set; }
[Parameter] public RenderFragment footerContent { get; set; }
[Parameter] public RenderFragment bodyContent { get; set; }
private async Task UpdatePopupVisible()
{
PopupVisible = false;
await PopupVisibleChanged.InvokeAsync(PopupVisible);
}
}
Then I have a component that implements this template(child), and then I have that component called with a button press(parent). What I want to know is if there is a way to bind the PopupVisible parameter from the parent without having to bind it the child and having the child pass it to the template. I haven't found a way to two-way bind a cascading parameter but if possible I think that would be the best way to do so. Outside of that, I'm not sure if there is another way or I'm going to have to go with my current idea of passing the value.
You can't do two-way binding with cascading parameters. Cascading means flowing downstream, from parent to child, and not the other way around.
I'm not sure I understand your question...however, if you wish to pass a value from a parent component and back; you can do the following:
Note: This is a two-way Component data binding
Child Component
#code
{
private bool visible;
[Parameter]
public bool PopupVisible
{
get { return visible }
set
{
if (visible != value)
{
visible = value;
}
}
}
[Parameter] public EventCallback<bool> PopupVisibleChanged { get; set; }
// Invoke the EventCallback to update the parent component' private field visible with the new value.
private Task UpdatePopupVisible()
{
PopupVisible = false;
return PopupVisibleChanged.InvokeAsync(PopupVisible);
}
}
Usage
#page "/"
<DxPopup #bind-PopupVisible="visible" />
#code {
private bool visible;
}
Note: If you need some explanation, and believe that I did not answer your question, don't hesitate to tell me, but please take the time to phrase your questions... I could not completely understand questions.
what you can do is, Cascade the parent component and in the child component, access the parent Property you want to change like this:
Parent:
<CascadingValue Value="this">
<Child />
</CascadingValue>
Child:
[CascadingParameter]
public Parent Parent { get; set; }
.....
private void ChangeParentProperty()
{
Parent.Property = ....;
}
Any doubt feel free to ask.