Search code examples
.netblazorref

Element reference null in 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?


Solution

  • 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();
      }
    }