How to embed a Razor component inside an element added on the JavaScript side

Viewed 108

Overview

In the Blazor WebAssembly App, I would like to embed a Razor component in a div element newly added on the JavaScript side. Please let me know if there is a better way.

What I want to do

  1. Prepare components such as Sample.razor in advance
  2. Call JavaScript functions in response to button clicks on the initial page
  3. Add div element by createElement in the called JavaScript function
  4. Embed the Sample.razor component within the div element added above

What I tried

  • Use innerHTML for the div element added in 3. above, and include a call tag for the Razor component.(<Sample></Sample>)

-> Nothing is shown.

  • Add elements such as iframe/object/embed in innerHTML and include the path to the razor component. (src='/sample')

-> Not Found. (Because this is a WebAssembly app, component pages are not rendered if we request to a server.)

Environment

  • Visual Studio 2019
  • .NET 5
  • Project creation from Visual Studio using Blazor WebAssembly template
1 Answers

If you have prepared the Simple.Razor component in advance, one way you can achieve this is assign this component under if condition as follows,

@If(visible==true){<div><simple></simple></div>}

and on press of a button change visible variable in a function followed by,

StateHasChanged()

and it will do what you want this way you dont have to do JSInjection.

Related