Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Element reference null in Blazor

Tags:

.net

ref

blazor

I have the following html razor code

<StEyth @ref="stEyth"></StEyth>
<Gr1D @ref="gr1D" ></Gr1D>

 

the following code in @code

@code {     
 private Gr1D?  gr1D;
 private StEyth? stEyth;
 protected override async Task OnInitializedAsync()    
 {
   await updateView();
 }
 private async Task updateView()    
 {
   DrpdVal = new IpDrpdValues { ar1 = gr1D.ar1}
   await stEyth.updateView(DrpdVal);
 }
}

But gr1D is null when the code reaches

DrpdVal = new IpDrpdValues { ar1 = gr1D.ar1}

Any idea why? And how could I get the values of the variables in the Gr1D?

like image 949
vagelis Avatar asked May 12 '26 12:05

vagelis


2 Answers

The @ref is set during the rendering. OnInitialized executes before the first render.

So the logical place to do this is in OnAfterRender. Use firstRender to do it only once.

protected override async Task OnAfterRenderAsync(bool firstRender)
{
  if (firstRender)
  {
    await updateView();
  }
}
like image 152
Henk Holterman Avatar answered May 14 '26 02:05

Henk Holterman


If you add a yield in front of the call to UpdateView then the component runs it's initial render and the child components exist.

    protected override async Task OnInitializedAsync()
    {
        await Task.Yield();
        await UpdateView();
    }

However, if I read your comment above correctly, you're trying to co-ordinate data exchange between components. This is pretty fraught with danger: you aren't in control of the render and update process. You should consider using a service to hold your data, and notification events your components can subscribe to.

like image 32
MrC aka Shaun Curtis Avatar answered May 14 '26 03:05

MrC aka Shaun Curtis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!