简体   繁体   中英

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM