Hi,
I am trying to implement databinding on a custom Blazor Component.
I know there is a Bind attribute and as an example, it works like this for the input field:
<input type="text" bind="@Name" />
But what about Custom components? I Can't do this:
<CustomComponent bind="@Name" />
So does anyone have an idea of how to make a custom component support databinding? :)
Thanks,
Jeppe
I Can't do this:
<CustomComponent bind="@Name" />
You can. For this two-way binding to work, your property needs something like the following pair of properties:
@functions {
[Parameter]
string Name { get; set; }
[Parameter]
Action<string> NameChanged { get; set; }
}
Blazor will look for these two.
Also see here: https://github.com/aspnet/Blazor/issues/610
Thanks for the answers! :)
I will try it out - it's difficult to find documentation explaining this :)
Hi again,
@chucker I cannot make what you suggest to work. I ended up doing what @floreseken mentions in the thread he linked to - but it's not real databinding since you control it yourself using events.
So i ended up with this component:
TestInput.cshtml:
@inherits BlazorDatabinding.Pages.TestInputComponent
<p>Enter a value:</p>
<input value="@TestValue" onchange="@ChildChanged" />
TestInput.cshtml.cs:
public class TestInputComponent : BlazorComponent
{
[Parameter]
protected string TestValue { get; set; }
[Parameter]
protected Action<string> TestValueChanged { get; set; }
protected void ChildChanged(UIChangeEventArgs e)
{
Console.WriteLine($"Child InputChanged: {(string)e.Value}");
TestValue = (string)e.Value;
TestValueChanged(TestValue);
}
}
And then i can use it like this:
<TestInput TestValue="@ParentValue" TestValueChanged="@ParentChanged"/>
And the parent needs to have this handler:
public void ParentChanged(string myValue)
{
Console.WriteLine($"ParentChanged: {myValue}");
ParentValue = myValue;
StateHasChanged();
}
Is this the only way to accomplish this at the moment?
If so i hope there comes an easier way of doing it :)
The mechanism described by @floreseken is what's currently implemented.
We plan to make it more automated in the way you're looking for. This work is tracked in https://github.com/aspnet/Blazor/issues/610
@SteveSandersonMS okay, that sounds great!
Have you scheduled in which release this will be implemented or is it currently unknown?
Thanks for the information - Big fan of the Blazor framework! :D
I've written a blogpost on a workaround which involves less code if you have a lot of components.
http://flores.eken.nl/blazor-custom-component-with-2-way-databinding/
Nice article @floreseken
Thanks for sharing that @floreseken . :)