The Question
I'm trying to load a JavaScript file in a child component and expose its methods to the parent. I've been able to load the file, but any time I try to use my methods outside of the child component, I get an error. I've provided a minimum example for reference.
I'm really stuck with why this isn't working... My thought is that is has something to do with the child component not being fully rendered. And I'm not really sure how to fix it.
Minimum Example
Page
// Page.razor
<ChildComponent @ref="Ref" />
@code {
private ChildComponent Ref;
protected override async Task OnAfterRenderAsync()
{
await Ref.Test();
}
}
Child Component
// ChildComponent.razor
@inject IJSRuntime JS
@code {
private IJSObjectReference Module;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
Module = await JS.InvokeAsync<IJSObjectReference>("import", "./ChildComponent.razor.js");
}
}
public async Task Test()
{
await Module.InvokeVoidAsync("Test");
}
}
// ChildComponent.razor.js
export function Test() {
alert("Hello world!");
}
