Search code examples
c#asp.net-corerazorblazorrazorengine

Is it possible to use a conditional construct to enable an attribute in Blazor?


Consider the following Razor component.

@code
{
    private bool isIndex = true;
}


@if (isIndex)
{
    <NavLink href="" Match=NavLinkMatch.All>
        Index
    </NavLink>
}
else
{
    <NavLink href="Other">
        Other
    </NavLink>
}

Is it possible to use a conditional construct to enable Match=NavLinkMatch.All that renders the same output as above?

<NavLink href=@(isIndex? string.Empty:"Other")>
    @(isIndex? "Index": "Other")
</NavLink>

Solution

  • Is it possible to use a conditional construct to enable Match=NavLinkMatch.All

    It is an enum with two values.

    You can just use Match="@(IsIndex ? NavLinkMatch.All : NavLink.Prefix)"
    Prefix is the default so you don't see it much.

    But more in general: no, you can only apply C# logic to the values of attributes. Unless you want to drop down to BuildRenderTree code.