Q:

How do you get child component bound values in the parent component?

0

This code will help you to understand how to get child component bound values in the parent component.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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, the 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;
    }
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now