How to access Custom Element from a JSLibrary that is Wrapped in C# Nuget Package - Blazor .NET

180 Views Asked by At

I've wrapped model-viewer JS library in a C# Razor Class Library and made it a Nuget package. However, different from other JS Libraries, Model-Viewer doesn't have many methods, it's main property is a Custom Element model-viewer and it's properties. Any ideas on how should I access this element after the library is wrapped in C#?

ModelViewerService.cs:

public class ModelViewerService
{
    private static Task<IJSObjectReference> s_module = null;

    private readonly IJSRuntime js;

    public ModelViewer(JSRuntime js)
    {
        Assembly asm;
        JS = js;

        if(s_module == null)
        {
            asm = Assembly.GetExecutingAssembly();
            s_module = JS.InvokeAsync<IJSObjectReference>("import", "./_content/ModelViewerPackage/scripts/model-viewer/model-viewer.min.js?version=" + asm.ManifestModule.ModuleVersionId).AsTask();
        }
    }
}

In my Index.blazor page, before when I was importing the Library directly through

<script src="model=viewer.min.js" type="module"></script>

I was loading my model simply by calling:

<model-viewer src="mymodel.glb"></model-viewer>

Will I be to use this library with this same syntax? Or do I need to make any kind of abstraction on my package?

1

There are 1 best solutions below

2
On

Ok, I've figured it out. I need to create a ModelViewerService object passing an Injected JSRuntime object and the library will be imported to my Blazor App from my package.

In Index.blazor.cs

[Inject]
private JSRuntime js;

protected override async Task OnInitializedAsync()
{
     this.StateHasChanged()
     await base.OnInitializedAsync();

     ModelViewerService modelViewer = new(js); // This will do the trick.
}