Author : MD TAREQ HASSAN | Updated : 2020/08/28
Passing Data From Child To Parent
Best way: EventCallback
Child.razor.cs
public class ChildBase : ComponentBase
{
[Parameter]
public EventCallback<Baz> OnSendBaz { get; set; }
[Inject]
public IFooService FooService { get; set; }
protected Bar Bar { get; set; }
protected override void OnInitialized()
{
Bar = new Bar();
}
protected async Task OnClickSend(MouseEventArgs args)
{
var baz = FooService.GetBaz(id: Bar.Id);
//Modal.Hide();
await OnSendBaz.InvokeAsync(baz);
}
}
Child.razor
@inherits ChildBase
<div class="form-group">
<input type="button" class="btn btn-primary btn-sm" id="" value="Send" />
</div>
Parent.razor.cs
public class ParentBase : ComponentBase
{
protected Baz ReceivedBaz { get; set; }
protected override void OnInitialized()
{
ReceivedBaz = new Baz() { Id = 0};
}
protected async Task OnReceiveBaz(Baz baz)
{
ReceivedBaz = baz;
}
}
Parent.razor
@inherits ParentBase
<label>Baz ID: @ReceivedBaz.Id</label>
<Child OnSendBaz="OnReceiveBaz"></Child>
Passing Data From Parent To Child
- Method 1 : use
@ref
- Method 2 : https://stackoverflow.com/a/60048925/4802664
Using @ref
//
// parent component
//
<ChildComponent @ref="@Child" />
<button onClick="@ShowModal">Show Child Modal</button>
@code{
protected ChildComponent Child {get; set;};
void ShowModal(){
Child.Modal.Show();
}
}