What is the @ref directive, and how do you use it to capture a reference to a child component or DOM element and call its methods?
Last updated
@refcaptures a child component instance (field typed as the component) to call its public methods, or anElementReferenceto pass to JS interop (e.g. focus).The reference is populated only after rendering, so use it in
OnAfterRenderAsync, notOnInitialized.Use it sparingly for imperative actions. Prefer parameters and callbacks for data flow.
- https://learn.microsoft.com/en-us/aspnet/core/blazor/components/?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/call-javascript-from-dotnet?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/blazor/components/event-handling?view=aspnetcore-10.0
- https://dev.to/stevsharp/mastering-blazor-component-communication-eventcallback-cascadingparameter-and-ref-explained-eig
- https://www.meziantou.net/calling-public-methods-on-blazor-component-from-another-component.htm