Tomas Am
Tomas Am

Reputation: 503

Styling Blazor EditForm components - focus on InputText

I am learning Blazor framework and it has it's own HTML elements. I tried to style InputText element, but however it does not seem to work with some CSS properties. For example "Focus".

My CSS:

    input:focus, select:focus, .inputstyle:focus {
        border: 1px solid #ff6801;
    }

HTML Input works fine, but InputText does not. My code:

<input type="text" name="address" id="address" />
<InputText class="inputstyle" @bind-Value="@Advert.Title" />

So how could I put css Focus on InputText?

Upvotes: 1

Views: 4460

Answers (1)

enet
enet

Reputation: 45724

InputText is a Blazor component, so it can't get input focus. But you can set focus on its internal input element... You can do something like this:

You can derives from InputText, and use ElementReference.FocusAsync()

Note: This feature is only available in .Net 5.0

InputTextSetFocus.razor

@inherits InputText
  
<input @ref="inputElement"
       @attributes="AdditionalAttributes"
       class="@CssClass"
       value="@CurrentValue"
       @oninput="EventCallback.Factory.CreateBinder<string>(this, __value => CurrentValueAsString = __value, CurrentValueAsString)" />

@code {
    private ElementReference inputElement;

    protected override void OnAfterRender(bool firstRender)
    {
         base.OnInitialized();
         inputElement.FocusAsync();
       
    }

   
}

Usage

@page "/"

<EditForm Model="employee">
    <InputTextSetFocus @bind-Value="@employee.ID" />
</EditForm>

@code
{
    private Employee employee = new Employee();

    public class Employee
    {
        public string ID { get; set; }
        public string Name { get; set; }
    }
}

Upvotes: 2

Related Questions