We can get child component values in the parent component by creating a reference to the child component using the @ref directive in the Parent component. Using the reference instance, you can access the child component values in the parent.
In the following example, textbox refers to the TextBoxComponent (child component) instance. Using textbox, we can access the properties and values in the Parent component.
[TextBoxComponent.razor]
<div class="form-group row mb-2">
<label class="col-md-3 col-form-label"
for="Name">@FieldName</label>
<div class="col-md7">
<input class="form-control"
type="text"
placeholder="@FieldName" value="@Value" @oninput="OnValueChanged" maxlength="@MaxLength" />
</div>
</div>
@code {
[Parameter]
public string Value { get; set; }
[Parameter]
public string FieldName { get; set; }
[Parameter]
public int MaxLength { get; set; } = -1;
[Parameter]
public EventCallback<string> ValueChanged { get; set; }
string LengthString;
int TextLength;
protected override void OnInitialized()
{
TextLength = Value.Length;
LengthString = (MaxLength == -1) ? "Unlimited" : MaxLength.ToString();
}
private Task OnValueChanged(ChangeEventArgs e)
{
Value = e.Value.ToString();
TextLength = Value.Length;
return ValueChanged.InvokeAsync(Value);
}
}
[Parent.razor]
@page "/parent"
<TextBoxComponent @ref="textbox" @bind-Value="name" FieldName="Name" MaxLength="20" />
<TextBoxComponent @bind-Value="address" FieldName="Address" />
<button @onclick="Click">Click </button>
@code {
TextBoxComponent textbox;
string name = "Rafael Nadal";
string address = "New York";
private void Click()
{
var fNme = textbox.FieldName;
var maxLen = textbox.MaxLength;
}
}
Share with