Venkat
Venkat

Reputation: 2186

ternary operation in blazor, convert a if-else statement into just one statement

I have the following code in a page.razor:

                    @if (i==1)
                    {
                        <MudTimelineItem  Color="Color.Primary" Size="Size.Medium" Variant="Variant.Outlined">
                            <MudAlert Severity="Severity.Success">@matrix.UserName</MudAlert>
                        </MudTimelineItem>
                    }
                    else
                    {
                        <MudTimelineItem   Variant="Variant.Outlined">
                            <MudAlert Severity="Severity.Success">@matrix.UserName</MudAlert>
                        </MudTimelineItem>
                    }

The only thing that changes is the color and size parameters, rest remains the same, Instead of using if-else statement can this be written in just one line using ternary operators or any other with which blazor supports?

Upvotes: 1

Views: 283

Answers (1)

Guru Stron
Guru Stron

Reputation: 143003

Blazor should not render attribute if it's value is null or false (docs). Try something like:

<MudTimelineItem Color="@(i == 1 ? Color.Primary : null)" Size="@(i == 1 ? Size.Medium : null)" Variant="Variant.Outlined">
    <MudAlert Severity="Severity.Success">@matrix.UserName</MudAlert>
</MudTimelineItem>

Upvotes: 2

Related Questions