Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

How to dynamically set an HTML header tag (h1, h2, etc.) in a Blazor component?

$
0
0

I want to create a reusable Blazor component that allows the user to define the HTML header tag (<h1>, <h2>, etc.) via a parameter.

My goal is to render a header dynamically like this:

<HeaderWithTooltip HeaderText="Invite" HeaderSize="3" TooltipText="asd"/>

The Component looks like this:

<MudStack Row="true" Spacing="1" AlignItems="AlignItems.Center"><DynamicComponent Type="@_headerTagType" Parameters="@_headerTagParameters" />    @if (!string.IsNullOrWhiteSpace(TooltipText))    {<MudIcon Icon="help" Style="color: var(--title-color)"><MudTooltip Text="@TooltipText"/></MudIcon>    }</MudStack>@code {    [Parameter] public required string HeaderText { get; set; }    [Parameter] public int HeaderSize { get; set; } = 1;    [Parameter] public string? TooltipText { get; set; }    private Type? _headerTagType;    private readonly Dictionary<string, object> _headerTagParameters = new();    protected override void OnParametersSet()    {        var validHeaderSize = HeaderSize is >= 1 and <= 6 ? HeaderSize : 1;    _headerTagType = Type.GetType($"Microsoft.AspNetCore.Components.Web.HtmlElement+h{validHeaderSize}, Microsoft.AspNetCore.Components.Web");    _headerTagParameters["class"] = "page-title";    _headerTagParameters["ChildContent"] = (RenderFragment)(builder => { builder.AddContent(0, HeaderText); });    }}

Which should result in the following HTML-Header:<h2 class="page-title">Invite</h2>

As you can see in my Code, when no HeaderSize is given, then the defaultvalue is used, which should result in an <h1>-Header

I tried to use Type.GetType to dynamically get the type for the HTML header tags (h1, h2, etc.) and pass it to the DynamicComponent.

I was expecting this to work and to render a different header tag depending on the provided HeaderSize parameter.

However, Type.GetType returns null.

Therefore, my component does not render any header tag, as the DynamicComponent's Type is null.


Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>