Home > Software engineering >  Combining Input and Button into an InputButton component
Combining Input and Button into an InputButton component

Time:08-01

Example

Let's suppose I have the following bit of code:

@code {
    private decimal abc = 0;
    private decimal bcd = 0;
}

<input @bind-value="abc"/>
<button>@abc</button>
<br />

<input @bind-value="bcd"/>
<button>@bcd</button>
<br />

If I change the input values, the buttons update:

enter image description here

Using InputButton component

Now, let's say I'd like to have an InputButton component which can be used to setup one of those input and button pairs.

In Shared\InputButton.razor I have:

@code {
    [Parameter]
    public decimal Val { get; set; }
}

<input @bind="Val" />
<button>@Val</button>

Now, if I update the original code to use an InputButton:

@code {
    private decimal abc = 0;
    private decimal bcd = 0;
}

<input @bind-value="abc"/>
<button>@abc</button>
<br />

<input @bind-value="bcd"/>
<button>@bcd</button>
<br />

<InputButton Val="abc" />

while it does render:

enter image description here

if I change the third input (generated by InputButton) it does not change abc. (As you can see there, I entered 3 into the input field but the first input and button did not change.

However, if I change the first input, the third is affected:

enter image description here

Question

What's a good way to have InputButton change the variable that is passed to it?

Live example

Here's a blazorfiddle which sets up the above:

https://blazorfiddle.com/s/i3wx120z

CodePudding user response:

You could use either a state service or a EventCallback , callback is simpler to implement for a parent/child set-up

[Parameter]
public EventCallback<decimal> ParentCallBack { get; set; }

private async Task HandleInputValueChange(KeyboardEventArgs e){
  Decimal.TryParse(e.Key, out decimal @parsedDec);
  await ParentCallBack.InvokeAsync(parsedDec);
}

Updated Fiddle

CodePudding user response:

Here's an approach that works:

@code {
    private decimal _value;

    [Parameter]
    public EventCallback<decimal> ValChanged { get; set; }

    [Parameter]
    public decimal Val 
    {
        get => _value;

        set
        {
            if (_value == value) return;

            _value = value;

            ValChanged.InvokeAsync(value);
        }
    }
}

<input @bind="@Val"/>
<button>@Val</button>

Blazor fiddle:

https://blazorfiddle.com/s/uvxvwvvy

  • Related