Blazor – Input Elements Reference – ASP.NET Core 6

A new feature of Blazor for ASP.NET Core 6 is that there is now a new property that allows us to access the input of the InputCheckbox, InputDate, InputFile, InputNumber, InputSelect, InputText, and InputTextArea components.

To use this feature we must make a reference to the element in question, say, an InputText, and use the Element property of it.

Let’s see an example:

<EditForm Model="model">
	<InputText @ref="inputTextReference" class="form-control" @bind-Value="model" />
</EditForm>

<button class="btn btn-primary" @onclick="HandleClick">Click me</button>

@code {
	InputText inputTextReference;
	string model = "";

	private void HandleClick()
	{
		if (inputTextReference.Element.HasValue)
		{
			inputTextReference.Element.Value.FocusAsync();
		}
	}
}

As we can see, we have an InputText inside an EditForm. We put the @ref attribute to anchor the InputText to the inputTextReference variable. Then, in the HandleClick method we use inputTextReference.Element to access the textbox as such. Notice that the Element property is of type ElementReference?, that is, it is nullable, that’s why we use HasValue to safely access the textbox.

As we said, we can do the same with other components such as: InputCheckbox, InputDate, InputFile, InputNumber, InputSelect, and InputTextArea.

Courses

If you want to learn more about Blazor, or about other technologies, get one of my Udemy courses with a discount:

  1. Building Applications with Angular 11 and ASP.NET Core 5: https://www.udemy.com/course/building-applications-with-angular-and-aspnet-core/?couponCode=JUNE2021
  2. Programming in Blazor – ASP.NET Core 5: https://www.udemy.com/course/programming-in-blazor-aspnet-core/?couponCode=JUNE2021
  3. Building RESTful Web APIs with ASP.NET Core 3.1: https://www.udemy.com/course/building-restful-web-apis-with-aspnet-core/?couponCode=JUNE2021
  4. Introduction to Concurrency in C# – Async and Paralellism: https://www.udemy.com/course/introduction-to-concurrency-in-c-async-and-paralellism/?couponCode=JUNE2021

Regards!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s