SamProf / MatBlazor

Material Design components for Blazor and Razor Components

Home Page:http://www.matblazor.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

MatSelect IsModified() from EditContext - With Workaround

mmuller88 opened this issue · comments

Describe the bug
The MatSelect together with the EditContext IsModified() only triggers on the second select.

<MatSelect Label="Parks" @bind-Value="context.Item1.ParkId" TValue="int">
    @foreach (var park in parks)
    {
        <MatOption Value="@park.Id">@park.Name</MatOption>
    }
</MatSelect>

To Reproduce
Steps to reproduce the behavior:

  1. Setup MatSelect with EditContext als wrapper
  2. Configure a Save Button which is disabled if nothing changed like <MatButton Disabled="!_editContext.IsModified()" ...
  3. Select an option

Expected behavior
Save button is not disabled

Actual behaviour
Save button is disabled

Workaround
Use onclick to make IsModified() working for the first select.

<MatSelect Label="@LChecklists["Checklistitem"]" @bind-Value="context.Item1.ChecklistItemId" TValue="int?">
        @foreach (var checklistItem in _checklistItems)
        {
            <MatOption @onclick="() => { context.Item1.ChecklistItemId = checklistItem.Id; }" Value="@checklistItem?.Id">@checklistItem?.Name</MatOption>
        }
</MatSelect>

Hi @mmuller88 !

I am not a big expert in Blazor and MatBlazor, but I tried to reproduce the issue and try to google some examples (about EditContext in general without linking to MatBlazor).

I found another workaround (or maybe it is expected behavior for Blazor at all)

protected override void OnInitialized()
{
    _editContext = new EditContext(_parkSelectorModel);
    _editContext.OnFieldChanged += (sender, args) =>
    {
        StateHasChanged();
    };
}

Full example: https://blazorfiddle.com/s/7v96wt7g

<EditForm EditContext="_editContext">
    <MatSelect Label="Parks" @bind-Value="_parkSelectorModel.ParkId" TValue="int">
        @foreach (var park in _parks)
        {
            <MatOption Value="@park.Id">@park.Name</MatOption>
        }
    </MatSelect>
    <MatButton Disabled="!_editContext.IsModified()">Save</MatButton>
</EditForm>


@code {
    EditContext _editContext;
    readonly ParkSelectorModel _parkSelectorModel = new ParkSelectorModel();
    readonly Park[] _parks = new Park[]
    {
        new Park()
        {
            Id = 1,
            Name = "Park 1"
        },
        new Park()
        {
            Id = 2,
            Name = "Park 2"
        }
    };

    protected override void OnInitialized()
    {
        _editContext = new EditContext(_parkSelectorModel);
        _editContext.OnFieldChanged += (sender, args) =>
        {
            StateHasChanged();
        };
    }

    public class Park
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    
    public class ParkSelectorModel
    {
        public int ParkId { get; set; }
    }
}