11
votes

I'm creating a blazor server side app and have problems to bind a value between two custom components.

I've looked through different example of how the bind or @bind is supposed to work but I cannot figure out what up to date information on this matter is.

Given a model class User:

public class User
    {
        [Mapping(ColumnName = "short_id")]
        public string ShortId { get; set; }

        public User()
        {

        }
    }

I want to build a form which displays all properties of this user and has them in an input so it can be edited and in the end saved to a database.

My Form (parent component) looks like this:

<div class="edit-user-form">
    <AnimatedUserInput TbText="@User.ShortId" Placeholder="MHTEE Id"/>
    <button class="btn btn-secondary" @onclick="Hide" style="{display:inline-block;}">Back</button>
    <button class="btn btn-primary" @onclick="SaveUser" style="{display:inline-block;}">Save</button>
</div>
@code {
    [Parameter] public vUser User { get; set; }

    [Parameter] public Action Hide { get; set; }

    bool _error = false;

    void SaveUser()
    {
        ValidateUserData();
    }

    void ValidateUserData()
    {
        _error = string.IsNullOrWhiteSpace(User.ShortId);
    }
}

Where AnimatedUserInput is a custom component that looks like this:

<div class="edit-area @FocusClass @WiggleClass">
    <input type="text" @bind="@TbText" />
    <span data-placeholder="@Placeholder"></span>
</div>
@code {
    [Parameter]
    public string TbText { get; set; }

    [Parameter]
    public string Placeholder { get; set; }
}

Now in the Input textbox I correctly see the ShortId of the User object in my parent component.

However if I change the text in the input and click on the Save button which triggers the ValidateUserData method and allows me to look at the current User object I see that no changes have been done in the actual User.ShortId property but only on the input.

Is there any way to bind it so that changes in the input will automatically be applied to the binded property?

I have several of these properies which need to be shown in the form which is why I dont want to hook a custom OnChanged Event for each of those properties.

3

3 Answers

20
votes

Ok so for anyone stumbling upon this. I tried a bit more and found a solution. So to my custom input component AnimatedUserInput I added a EventCallback which I call everytime the value on the input is updated:

@code {

    [Parameter]
    public string TbText
    {
        get => _tbText;
        set
        {
            if (_tbText == value) return;

            _tbText = value;
            TbTextChanged.InvokeAsync(value);
        }
    }

    [Parameter]
    public EventCallback<string> TbTextChanged { get; set; }

    [Parameter]
    public string Placeholder { get; set; }

    private string _tbText;
}

And the binding on my parent component looks like this:

<div class="edit-user-form">
    <AnimatedUserInput @bind-TbText="@User.ShortId" Placeholder="MHTEE Id"/>
    <AnimatedUserInput @bind-TbText="@User.FirstName" Placeholder="First name" />
    <AnimatedUserInput @bind-TbText="@User.LastName" Placeholder="Last name" />
    <AnimatedUserInput @bind-TbText="@User.UserName" Placeholder="Username" />
    <AnimatedUserInput @bind-TbText="@User.StaffType" Placeholder="Staff type" />
    <AnimatedUserInput @bind-TbText="@User.Token" Placeholder="Token" />
    <button class="btn btn-secondary" @onclick="Hide" style="{display:inline-block;}">Back</button>
    <button class="btn btn-primary" @onclick="SaveUser" style="{display:inline-block;}">Save</button>
</div>

@code {
    [Parameter] public vUser User { get; set; }
}

This way blazor can correctly bind the values together and updates them from both sides the way I would expect them to bind.

0
votes

This is how i achieved two way binding

Parent Component

<LabelledField Class=""
   Label="Label value"
   DateValue="@Model.Value"
   OnDateChange="@((e) => Model.Value = e )"
   Type="InputType.date" />

Child Component

<div class="@Class">
<div class="ft-07 mb-03 field-label @LabelClass">@Label</div>
@switch (Type)
{
    case InputType.constant:
        <div class="label-field-value @ValueClass">@Value</div>
        break;
    case InputType.text:
        <input class="form-control input @ValueClass"
               type="text"
               @bind="Value" />

        break;
    case InputType.date:
        <input class="form-control input @ValueClass"
               type="date"
               @bind="DateValue" />

        break;
    default:
        break;
}
@code{
private string _tbText;
private DateTime? _tbDate;

[Parameter]
public string Class { get; set; }

[Parameter]
public string Label { get; set; }

[Parameter]
public string LabelClass { get; set; }

[Parameter]
public string Value
{
    get => _tbText;
    set
    {
        if (_tbText == value) return;

        _tbText = value;
        OnTextChange.InvokeAsync(value);
    }
}

[Parameter]
public DateTime? DateValue
{
    get => _tbDate;
    set
    {
        if (_tbDate == value) return;

        _tbDate = value;
        OnDateChange.InvokeAsync(_tbDate);
    }
}

[Parameter]
public string ValueClass { get; set; }

[Parameter]
public InputType Type { get; set; } = InputType.constant;

[Parameter]
public EventCallback<string> OnTextChange { get; set; }

[Parameter]
public EventCallback<DateTime?> OnDateChange { get; set; }
}
0
votes

Thank you for the examples you guys posted here. Using them, I did a custom input checkbox two-way binding component based on the Toggle Switch example from W3schools' How TO-Toggle Switch like this one:

enter image description here

It triggers the event when it changes its status.

The Component

<div class="@Class">
    <label class="switch">
        <input id="@Id" type="checkbox" @bind="IsOn" />
        <span class="slider round"></span>
    </label>
</div>

@code {
    [Parameter] public EventCallback<bool> OnToggle { get; set; }
    [Parameter] public string Id { get; set; }
    [Parameter] public string Class { get; set; }
    [Parameter] public bool SetAsChecked { get; set; }

    private bool _isSettingUp = true;
    private bool _isOn;

    protected override Task OnInitializedAsync()
    {
        IsOn = SetAsChecked;
        return base.OnInitializedAsync();
    }

    private bool IsOn
    {
        get => _isOn;
        set
        {
            _isOn = value;
            if (!_isSettingUp)
            {
                OnToggle.InvokeAsync(value);
            }
            _isSettingUp = false;
        }
    }
}

The _isSettingUp flag is the way I found not to trigger the EventCallback when the check is set on at first. Maybe someone finds a better way to deal with that.

The Parent

(here is where you use your component)

<ToggleSwitch Id="mySwitch" OnToggle="((isChecked)=>DoSomething(isChecked))" SetAsChecked="isChecked" />

@code {
    private bool isChecked;

    protected override void OnInitialized()
    {
        isChecked = true;
    }

    protected void DoSomething(bool isChecked)
    {
        Console.WriteLine($">>>> {isChecked} <<<<");
    }
}

The CSS

The CSS is adapted from the W3Scholl example here. It should be placed in a .razor.css file named as the component (in the same folder) if you want to take advantage of Blazor CSS Isolation. Then you can use the Class parameter of the component to adapt it to different needs.

.switch {
    position: relative;
    display: inline-block;
    width: 60px;
    margin-top: 7px;
}

    .switch input {
        opacity: 0;
        width: 0;
        height: 0;
    }

.slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    padding-top: 2px;
    background-color: #737272;
    -webkit-transition: .7s;
    transition: .7s;
    width: 62px;
    height: 29px;
}

    .slider:before {
        position: absolute;
        content: "\2716";
        text-align: center;
        color: dimgrey;
        height: 25px;
        width: 25px;
        left: 2px;
        bottom: 2px;
        padding-top: 1px;
        background-color: white;
        -webkit-transition: .8s;
        transition: .8s;
    }

input:checked + .slider {
    background-color: limegreen;
}

    input:checked + .slider:before {
        -webkit-transform: translateX(33px);
        -ms-transform: translateX(33px);
        transform: translateX(33px);
        content: "\2714";
        text-align: center;
        color: dodgerblue;
    }

.slider.round {
    border-radius: 20px;
}

    .slider.round:before {
        border-radius: 50%;
    }

By the way, you can put any HTML Symbol in the switch. I did pick these from this cool page that has a search and the CSS code, which is what we need if we add the symbol in the CSS content, as here.

Hope this is of use to someone.