I neet to get count from stockcomponents on My Parent component using child. For this code Count got 0 but actually data having more
<Heading Size="HeadingSize.Is4">Count @ItemCount Entries</Heading>
<StockComponent @ref=stockComponent />
StockComponent stockComponent;
int ItemCount ;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if(firstRender)
{
ItemCount = stockComponent.Count();
StateHasChanged();
}
}
** My StockComponent **
private int count;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if(firstRender)
{
Items = await db.Item.ToListAsync();
count = Items.Count;
StateHasChanged();
}
}
public int Count ()
{
return count;
}
CodePudding user response:
You need two-way binding. Also:
- get items in
OnInitializedAsync()
- you don't have to call
StateHasChanged()
CodePudding user response:
The way you code is wrong. What you need do is create a one-way data binding from the child to the parent (Child-to-parent binding). Your child component may look something like that:
StockComponent.razor
<button class="btn btn-primary" type="button"
@onclick="Increment">Increment<button>
@code
{
private int count;
private List<int> Items;
[Parameter]
public int Count { get; set; }
[Parameter]
public EventCallback<int> CountChanged { get; set; }
private async Task Increment()
{
count ;
await CountChanged.InvokeAsync(count);
}
// Note: You shouldn't use the life cycle OnAfterRenderAsync method as you
// do. Instead, you should use the OnInitializedAsync method, which is called
// only once, when the component is created, and initialized with values.
protected override async Task OnInitializedAsync()
{
Items = await db.Item.ToListAsync();
count = Items.Count;
await CountChanged.InvokeAsync(count);
}
}
Parent component: Index.razor
<div>Count: @ItemCount Entries</div>
<StockComponent @bind-Count="ItemCount" />
@code
{
private int ItemCount;
}
Copy and test...
Read about component binding in the docs
How can i get properties from child component in blazor
By defining parameter properties and event call backs. You cannot and should not capture a reference (@ref) to a component, and then initialize its properties. You may get an error or at least a warning. Use a reference (@ref) to a component only if you want to call a method that performs an operation such as showing a dialog within the called component.