hablahat
hablahat

Reputation: 192

Blazor event after @bind

In a Blazor page I have a collection of checkbox input elements bound to a boolean property with code

foreach(var item in items)
{
   <input type="checkbox" class="checkbox" @bind="@item.IsReady" @onclick="((e)=>ItemIsReady(item))" />
}

I'm looking for a way to trigger the function ItemIsReady after the binding has completed. Currently the function triggers before the binding has completed.

Some form of @bind directive is necessary because the page loads the items, and ready items need to be appear checked after loading.

I can't use a function in the property setter.

Anyone know how to do this?

Upvotes: 1

Views: 1176

Answers (1)

MrC aka Shaun Curtis
MrC aka Shaun Curtis

Reputation: 30001

"I'm looking for a way to trigger the function ItemIsReady after the binding has completed. Currently the function triggers before the binding has completed."

I'm assuming you want to react to changes make to the checkboxes. Maybe I'm wrong.

If you want to catch update events then you either:

  1. Use bind and catch the events on the property setter or
  2. Wire up the input manually.

The demo page below shows how you can do that:

@page "/Test"
@foreach (var item in model)
{
    <div><input type="checkbox" class="checkbox" checked="@item.IsReady" @onchange="((e)=>ItemIsReady(e, item))" /> <span>@item.IsReady</span></div>
}

@code  {

    List<ModelClass> model { get; set; } = new List<ModelClass> { 
       new ModelClass(), 
       new ModelClass() { IsReady=true }, 
       new ModelClass() 
    };

    class ModelClass
    {
        public bool IsReady { get; set; }
    }

    void ItemIsReady(ChangeEventArgs e, ModelClass item)
    {
        item.IsReady = (bool)e.Value;
    }
}

Upvotes: 2

Related Questions