Reputation: 491
I would like to know, how it is possible to call a component with a @typeparam
which comes from the URL
As it has been already discussed in C# Blazor: How to use @typeparam in Code behind? (with workaround), I built a component like Roger Wolf did in his solution.
Raozor.cs using Microsoft.AspNetCore.Components;
namespace BlazorApp1.Components
{
public partial class MyCustomComponent<T> : ComponentBase
{
[Parameter]
public string Label { get; set; }
}
}
The Razor part:
@namespace BlazorApp1.Components
@typeparam T
<label>@($"{Label}. Provided type is {typeof(T).Name.ToUpper()}")</label>
Index.razor page
@page "/{typeName}"
@using BlazorApp1.Components
<MyCustomComponent T="@TypeName" Label="Custom component label" />
@code
{
[Parameter]
public string TypeName {get; set;}
}
So the Line where I try to set the Type by the string property I get en compiler error. (I guess that internal an typeof() function will determine the type for the component class.) It will only compile, if I use an fixed coded type. :
e.g.: <MyCustomComponent T="long" Label="Custom component label" />
What I want to do is pull the type parameter from URL. Any ideas to get this work?
Upvotes: 4
Views: 3313
Reputation: 17404
The type of @typeparam
is deduce at compile time and you should have a parameter of type T
in your component:
namespace BlazorApp1.Components
{
public partial class MyCustomComponent<T> : ComponentBase
{
[Parameter]
public T MyParameter { get; set; }
}
}
It's use to make generic component, you cannot use it as your sample.
Upvotes: 1