How to make two-way binding on Blazor component

百般思念 提交于 2019-12-13 16:03:50

问题


I want to create custom input, so I created this component:

MyInputComponent.razor:

<div>
  <input type="text" @bind="BindingValue" />
</div>

@code {
    [Parameter]
    public string BindingValue { get; set; }
}

Then the usage:

<EditForm Model="model" OnValidSubmit="Submit">
    <MyInputComponent BindingValue="model.Name" />
</EditForm>

@code {
    User model = new User() { Name = "My Name" };

    private void Submit()
    {
       // here I found model.Name = null;
   }
}

When I debug MyInputComponent, I found the value as I have entered. But when I submit the form, the value is null.

How to do it ?


回答1:


Quoting Blazor docs:

Component parameters

Binding recognizes component parameters, where @bind-{property} can bind a property value across components.

For your page:

<EditForm Model="model" OnValidSubmit="Submit">
    <MyInputComponent @bind-BindingValue="model.Name" />
</EditForm>

The child component MyInputComponent:

<div>
  <InputText type="text" @bind-Value="@BindingValue" />
</div>

@code {

    private string _value;

    [Parameter]
    public string BindingValue
    {
        get => _value;
        set
        {
            if (_value == value ) return;
            _value = value;
            BindingValueChanged.InvokeAsync(value);
        }
    }

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

}

Notice you should to raise binding changes from children component through EventCallback<string> BindingValueChanged.

Try it at BlazorFiddle.



来源:https://stackoverflow.com/questions/57932850/how-to-make-two-way-binding-on-blazor-component

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!