Reputation: 1297
Considering this dialog below, how do I:
Create
button default (or submit) button?MudTextField
to submit on return (enter) key press?Adding ButtonType="ButtonType.Submit"
doesn't seem to change anything.
<MudDialog IsVisible="true" Class="pa-4" >
<DialogContent>
<MudTextField @bind-Value="NewName" Label="Name" Variant="Variant.Outlined" />
</DialogContent>
<DialogActions>
<MudButton Variant="Variant.Filled" OnClick="CloseCreateNewNameDialog">Cancel</MudButton>
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="CreateNewName">Create</MudButton>
</DialogActions>
</MudDialog>
Thanks!
Upvotes: 0
Views: 2496
Reputation: 121
A more universal approach is possible using KeyInterceptorFactory provided by MudBlazor allows to "subscribe" to any keypress that occurs within our form. In the example below the "Enter" key is hooked up to an event handler that validates and submits the form. Make sure to unsubscribe from the event and dispose of the KeyInterceptor instance.
@implements IDisposable
@using MudBlazor.Services
@inject IKeyInterceptorFactory KeyInterceptorFactory
...
<MudForm Model="@entity" @ref="@form">...</MudForm>
...
@code {
private string _elementId = "dialogcontainer_" + Guid.NewGuid().ToString().Substring(0, 8);
private IKeyInterceptor? _keyInterceptor;
protected bool IsJSRuntimeAvailable { get; set; }
MudForm? form;
protected override void OnAfterRender(bool firstRender)
{
IsJSRuntimeAvailable = true;
base.OnAfterRender(firstRender);
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
_keyInterceptor = KeyInterceptorFactory.Create();
await _keyInterceptor.Connect(_elementId, new KeyInterceptorOptions()
{
TargetClass = "mud-form",
Keys = {
new KeyOptions { Key="Enter", SubscribeDown = true },
},
});
_keyInterceptor.KeyDown += HandleKeyDown;
}
await base.OnAfterRenderAsync(firstRender);
}
internal void HandleKeyDown(KeyboardEventArgs args)
{
switch (args.Key)
{
case "Enter":
_ = Submit();
break;
}
}
private async Task Submit()
{
if (form != null)
{
await form.Validate();
if (form.IsValid)
{
SaveEntity();
}
}
}
void IDisposable.Dispose()
{
if (_keyInterceptor is not null)
{
_keyInterceptor.KeyDown -= HandleKeyDown;
}
if (IsJSRuntimeAvailable)
{
_keyInterceptor?.Dispose();
}
}
Upvotes: 0
Reputation: 624
To make the create button submit you have to use the Form tag from MudBlazor : https://mudblazor.com/components/form#simple-form-validation
<MudButton Variant="Variant.Filled" ButtonType="ButtonType.Submit" Color="Color.Primary" OnClick="CreateNewName">Create</MudButton>
and to enable MudTextField to submit on return on keypress, use the EventCallBacks OnKeyPress
Upvotes: 1