Jure Fadiga
Jure Fadiga

Reputation: 185

Blazor if condition change on button click

I created a test project where I am working on dynamically changing the html content based on if, else if conditions. The entire functionality is in one razor page. Currently the html does not update on code change:

@page "/condition"

<h3>Condition</h3>

<table>
    <thead>
        <tr>
            <td>Name</td>
            <td>Number</td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>First</td>
            <td>First</td>
        </tr>
        @if (second == true)
        {
            <tr>
                <td>Second</td>
                <td>Second</td>
            </tr>
        }
        else if(third == false)
        {
            <tr>
                <td>Third</td>
                <td>Third</td>
            </tr>
        }
    </tbody> </table> <button class="btn btn-primary" @onclick="@ChangeThird">Click me</button>


@code {
    bool second = true;
    bool third = true;

    private void ChangeThird()
    {
        third = false;
        StateHasChanged();
    } }

How do I make Blazor read the changes in the third property and display the new row ?

Upvotes: 1

Views: 2277

Answers (1)

enet
enet

Reputation: 45626

Just change this:

else if(third == false)
    {
        <tr>
            <td>Third</td>
            <td>Third</td>
        </tr>
    }

to:

@if(third == false)
        {
            <tr>
                <td>Third</td>
                <td>Third</td>
            </tr>
        }

In short, remove: else

Incidentally, the StateHasChanged method is called automatically...

Hope this helps...

Upvotes: 2

Related Questions