Blazor conditional if statement for onclick

Viewed 7706

I have a span which should have an onclick attribute if the IsActive bool is true. Otherwise the span should have no onclick attribute.

e.g.

@if (IsActive == true)
{
    <span @onclick="@(e => Go.DoSomething("please"))">
        @s.DisplayText
    </span>
}
else
{
    <span>
        @s.DisplayText
     </span>
}

Is there not a way to avoid the repeated code using a ternary operator? e.g.

@(IsActive == true ? "add onclick method somehow?" : "")
4 Answers

A better way to add the condition IsActive == true is in the Go.DoSomething method. But ideally I would have used a button if its clickable because we can add a disabled attribute to a button, in your case you can add the condition inside the onclick method.

Just a tip for the button, you can just add your c# boolean property within that attribute like this:

<button disabled="@IsActive">Save</button>

You can do the following.

<span @onclick="@(e => { if (IsActive) Go.DoSomething("please");})">
    @s
</span>

A Lambda Expression is what I think you are really looking for.

Just want to add something for people having a similar problem:

If you have more HTML code than a single span and you would need it twice because of an if-else-statement, I would create a own Blazor component (e.g. MyComponent.razor) and use component parameters. This way you don´t have much duplicate code in an if-else-statement.

Other answers are kind of wrong. There is a difference between registering an event method as a lambda and not registering an event if not necessary.

If you move the condition to a lambda function, anytime someone click your method will run. It would have a performance impact on your app, especially if it is Blazor Server since the round trip has to happen and the logic happens on your server.

@ondclick=@(Active?() => Go.DoSomething:null)

will not register the event if it is not active so no load on your server.

from Blazor Repository Tests

Related