I want to create custom input, so I created this component:
MyInputComponent.razor
:
Quoting Blazor docs:
Component parameters
Binding recognizes component parameters, where @bind-{property} can bind a property value across components.
For your page:
The child component MyInputComponent
:
@code {
private string _value;
[Parameter]
public string BindingValue
{
get => _value;
set
{
if (_value == value ) return;
_value = value;
BindingValueChanged.InvokeAsync(value);
}
}
[Parameter]
public EventCallback BindingValueChanged { get; set; }
}
Notice
EventCallback BindingValueChanged
.BindingValue
and BindingValueChanged
as identifiers, but, you can use just Value
and ValueChanged
. Then will be:
Try it at BlazorFiddle.
Edited: See Option 2 below for a clean solution:
If you want to put your component inside an EditForm and deal with validations, or take other actions using the onchange event, you should to raise EditContext.NotifyFieldChanged
. You have 2 options to do it.
You can get EditContext
from CascadeParameter
and invoke NotifyFieldChanged
by hand:
[CascadingParameter] EditContext EditContext { get; set; } = default!;
[Parameter] public Expression>? ValueExpression { get; set; }
#endregion
#region bindedValue
[Parameter] public EventCallback ValueChanged { get; set; }
private string _value { set; get; } = "";
[Parameter]
public string Value
{
get => _value;
set
{
if (_value == value) return;
_value = value;
ValueChanged.InvokeAsync(value);
var fieldIdentifier = FieldIdentifier.Create(ValueExpression);
EditContext.NotifyFieldChanged(fieldIdentifier);
}
}
You can inherit from InputBase
and just implement TryParseValueFromString
. InputBase
will do the work for you,When you inherit from InputBase you have Value
, ValueChanged
, EditContext
, etc.
protected override bool TryParseValueFromString(string? value, out string result, [NotNullWhen(false)] out string? validationErrorMessage)
{
result = value ?? "";
validationErrorMessage = null;
return true;
}