How to Consume a Blazor Component as a Web Component Within a Regular Non-Blazor HTML Page

Can we consume a Blazor component as a Web Component within a regular non-Blazor HTML page?

MS has addressed this limitation, but the solution requires .Net 6.

https://github.com/aspnet/AspLabs/tree/main/src/BlazorCustomElements

This was done by the man himself, Steve Sanderson.

Is it possible to embed a Blazor component in a non .NET website?

Yes. This is possible. Once you publish client-side Blazor application using dotnet publish resulting files can be served from any static file hosting. For example you could serve the results using http-server . from the folder where results are published.

To control appearance where Blazor application would be visible in the final HTML application, you can augment index.html as you see fit. <app> tag would be replaced by Blazor application.

Use Blazor as a Component

I would put this as a comment but I don't have the rep. I have been wondering the same and can only seem to find examples of rendering js/react components from inside a blazor app, not the other way around. A related issue has been raised on GitHub at https://github.com/dotnet/aspnetcore/issues/13766

Component tag does not render blazor component when the razor page is not directly in the pages folder

Instead of adding the blazor script on each page, I added two things in the _Layout.cshtml page.

In the head tag

<base href="~/" /> 
<component type="typeof(HeadOutlet)" render-mode="Server" />

Below the footer tag

<script src="_framework/blazor.server.js"></script>

How to render a Blazor component into an HTML string

Yes, you can use the test library provided by Steve Sanderson and adapt it to your needs.

This article explains how to use it : Introduction to Blazor Component Testing
.

The library can be use to generate the HTML of a component.

exemple :

var host = new TestHost();
var component = host.AddComponent<YourComponent>();
var html = component.GetMarkup();

And you can inject services you need.

host.ConfigureServices(services => 
{
service.AddSingleton<MyService>();
});


Related Topics



Leave a reply



Submit