Dynamic Component in Blazor
This blog is going to explain what a Dynamic Component is and how to use it. It is a built-in component used to render components by type. The Dynamic Component has two arguments which are type and parameter. Type is a component type and parameter is the parameter to be sent to the component.
Let's see how to implement Dynamic Components in Blazor. Below is a basic example of how to implement Dynamic Components. The "typeof(Counter)" is assigned to the Type property. It will render the Counter component in the index page.
index.razorThe following image is the output of the code snippets above. You can see here the Counter Component is rendered by Dynamic Component.
Pass Parameter
Let us see how to send the parameter to the component. The Dynamic Component sends the parameter as IDictionary<string, object>. The string is the name of the parameter and the object is the value of the parameter.
The following is a counter.razor component. Here I have added two property variables Title and current number with [parameter] attribute. These property variables receive values from Dynamic Components.
Counter.razorIn the below coding the parameters are passed as a dictionary.
index.razorThe following image is the output of the code snippets above. In the image you can see the title "Counter Demo" and the current count "20" is displayed.
Let’s see another example. Here I have created a ComponentMetadata.cs class file.
ComponentMetadata.csIn the below code, a dropdown is added to select a required component name. In the select element option I have added Counter and FetchData components.
index.razorThe output of the code above is below. As you can see here, when the user selects a component from the drop-down, it renders to the page with its parameter.
I hope this helps you. Keep coding.
Comments
Post a Comment