Handling UI Events in Blazor Web Apps [Pt 6] | Front-end Web Development with .NET for Beginners

dotnet www.youtube.com

Brief Summary

This video tutorial explains how to handle UI events in Blazor applications. It covers defining event handlers, handling events from web UI elements and custom components, passing content to a button element, and using additional attributes. Key points include:

  • Defining event handlers using synchronous or asynchronous methods, Lambda expressions, and code actions.
  • Handling events like onchange, oninput, onmouseover, and onmouseout on web UI elements.
  • Creating custom components with events and passing child content using RenderFragment.
  • Using CaptureUnmatchedValues to handle additional attributes on custom components.

Intro

The video introduces handling UI events in Blazor components, focusing on how web UI elements trigger events in response to user interactions and how to manage these events using C# code.

Define an event handler

The video explains different ways to define event handlers for events in Blazor. You can define event handlers using synchronous or asynchronous methods. For asynchronous methods, async Task is used, and await Task.Delay can simulate asynchronous behavior. Lambda expressions can be used directly within the attribute value for concise event handling. Visual Studio's code actions can generate synchronous or asynchronous event handlers, including an optional event argument providing additional event properties.

Handling events from web UI elements

The video demonstrates handling events from web UI elements, such as input fields and divs. The onchange event fires when an input loses focus, while the oninput event fires with every keystroke. Event arguments can be used to access the value of the input, which may require casting to the appropriate type. Blazor automatically rerenders the component after a UI event is handled. The video also shows how to handle onmouseover and onmouseout events on a div, changing the text content based on the mouse's position. Expression-bodied methods are used for concise event handlers.

Handling events from custom components

The video explains how to handle events from custom components by creating a MyButton component with an onclick event. An EventCallback<MouseEventArgs> parameter is defined to allow users of the component to register event handlers. The component's internal button click event invokes the onclick event callback, passing along the MouseEventArgs. This allows the parent component to handle the button click event raised by the custom component.

Passing content to a button element

The video describes how to pass content to a custom button element using a RenderFragment parameter named ChildContent. This allows the component to capture the content between the opening and closing tags of the MyButton component and render it inside the HTML button. The RenderFragment captures the chunk of Razor stuff and renders it someplace else.

Additional attributes

The video explains how to handle additional attributes on a custom component using a dictionary of type Dictionary<string, object> and the CaptureUnmatchedValues property. By setting CaptureUnmatchedValues to true on the parameter attribute, any additional attributes specified on the component are captured in the dictionary. The @attributes directive is then used to render these additional attributes on the HTML button, allowing users to pass along attributes like class for styling.

Summarize any YouTube video in seconds

Get summaries like this one for any video, in your language, with the free Summ app.

Download on the Apple Store
Get it on Google Play

Transcript

Full transcript of “Handling UI Events in Blazor Web Apps [Pt 6] | Front-end Web Development with .NET for Beginners”. Click a timestamp to open the video at that moment. Need another video? Use the YouTube transcript generator.

0:01 [Music] hey Blazer friends I'm Daniel Roth from the Blazer team in this video we're going to look at how you can handle UI events from your Blazer components web UI elements can trigger all sorts of events in response to user interactions and you can handle those events from your C code let's check it out out all right so here in our Blazer web app project we've already seen how you can handle a click event on a a button in our counter component we've got this button and we can see that over here we're uh wiring up an event handler for the onclick event with our increment

0:48 count method which is defined Below in below in the code block now there's actually a a few different ways that you can define an event handler for an event here we're just uh specifying the the method name and defining the method and it's a synchronous method that takes no arguments but we could instead do an asynchronous method so for example let's do uh async task increment count async just so it has a different name uh same logic current count Plus+ we'll save that format a little bit okay and then if we change the method up here to increment count A6 think we save that that should then apply to our running application just saw the check mark and

1:34 if we click the button it still works just as before show that it's actually doing something async let's add a await of task. delay right here so this will be a uh sluggish a sluggish counter all right every time we click now watch I'm going to click 1 1,000 and then an increments or click 1 1,000 then an increments so we can have an asynchronous event handler as well as synchronous one um we also can just instead of Def specifying a method name we can just put a a Lambda expression right here in the attribute value like we might say you know let's just whenever this onclick event happens let's take the current count let's get some intelligence going and we'll just increment it right there in line no problem let's see do that uh

2:22 I click that yep that's still working let's just just to show that it's doing something different that's increment by two we'll save that hot reload it and and we're able to go let's actually get this side by side so we can see both changes when we're playing with things all right cool um so you can do Lambda Expressions that that works as well now we that means we could get rid of these existing event handler methods now if you were starting from scratch like let's say you were just typing out like add-on click and you can type the method name that you want to to use right here like increment count and then you'll notice there's this little light bulb that popped up over here or you can trigger it by hitting uh control Dot and that will show you this code action to generate either a synchronous or asynchronous event handler for that that

3:07 event and it knows what type of event it is let's do the the synchronous one and this looks pretty similar to what we had before but now it has uh an event argument has this mouse event args argument um that let's take a look at what that's got so it's got a few additional properties about the event that was was just fired so as we've seen like that that argument is obviously optional you don't need to have it but you can include it uh and there are various um event ARG types for the different kinds of events so we could add our code back here you know current count Plus+ and then we should be back and running now with a event handler method and I think I might need to get Don it watch the restart right there we go we go in yes

3:54 we're going okay so those are the different patterns for how you can uh Define uh event handlers synchronous or asynchronous with an event ARG or without um and you can use the code action to to generate them all right let's try some of different events what about like on change for an an input let's add an input uh UI element right here and I want to take the value of this input and save it in a variable so let's let's add a a string it's just going to be text we'll default it to empty string and what I want to have happen is every single time this input changes so at on change equals and I'm going to create an onchange event handler method let's use

4:40 the code action we'll generate an onchange method which is now below and then we should be able to take the text variable that defined above and we want to get now the value of that that input and we can use the event ARG to do that so if we go and look at the event ARG there is a value property that we can use to get get its current value now the the the type of that value property is like just an an object I want it as a string I know it's going to be a string because this is a text input so I'm just going to go ahead and cast it uh to a string and let Visual Studio know it's not going to be null okay so we can do that and so now uh to show that that's working let's render the value of the the text variable below and save that let's see what that looks like okay our

5:26 formatting doesn't look great uh let me just fix that real quick let's put a little little div around our input there we go and we'll format and then maybe add a little padding up here up top using bootstrap so margin top three so that's space down a little bit okay that looks better so now if I type in this um input you know ABC nothing happens yet but if I uh tab away you know change the focus that onchange event fires which then calls my event handler and which gets the value of the input sets it to the variable and the component renders and we see the uh the value of the input R rendered below so notice that Blazer will automatically rerender the component uh after our UI event has been

6:12 handled that's just something it it it does a sort of a a a heuristic it assumes if you're you're F if you're wired up to an event handler something's probably changed and the component needs to to rerender okay that's cool uh what if we want the this to actually update though like every single time I type well we can do that as well let's go back to our input and instead of doing on change let's do on input which will fire every single time we type we probably want to rename this method I can do that by hitting F2 and that giv brings up the rename refactoring so on input and that should rename it below and it does all right save that and now as I type you can see that the uh the the the text value is being updated with

6:57 every uh with every keystroke all right cool so that's on change and on input um let's do uh one more let's do um let's do a div here below let's do another div and inside this div I want to render some text so let's uh Define another string variable um div text I guess and by default this is going to be Mouse out and you'll see why in just a second gives you a little hint to what events we're going to handle and I'm going to render that text inside the div um div text just like that and let's give the div some color just so that we can see it so I'm put a little inline style right here just because I'm lazy background color Andy background color let's make it I know light blue uh good

7:45 and then let's add a couple events here let's do at on Mouse over okay and we'll create an event handler for that Mouse over uh control dot to generate the event handler cool there's Mouse over and in here what we're going to do is we're going to change the div text to be Mouse over so that we know the mouse is actually over you know it's getting a little little verbose to have all these short little methods you can see that there's a little code action here that's saying Hey do you just want to use an expression body for this method ah yeah that's that's much nicer okay so let's let's do that for for all of these make them a little tighter it's a nice CP feature change these all to expression bodied functions so we don't have all don't need all those curly braces for

8:31 these single expression methods okay so that's Mouse the mouse over method we want to do one more let's do add on so we got have multiple event handlers on the div uh Mouse out okay let's do mouse out for that one again use our little code action Mouse out and there it is okay so for here we'll set the div text to be Mouse out like we had set it as the default okay change this to be an expression body method and we should be good to go okay so let's refresh the page my my color did I mess up my color light T light blue okay so now we've got this div that's got a light blue background when I Mouse over it the text changes to Mouse over when I Mouse out

9:18 the text changes to Mouse out and my input is still working and yeah so that's how you can handle uh events from web UI elements okay that's great um what about from a component what if I have a custom component that I also want to have uh an event that I can then handle from the component that's using it can I do that as well and the answer is yes of course you can do that too uh to show that let's actually add another component to our application I'm going to add it to this components folder I'm just going to click this new file icon and let's create a new razor component and we're going to call this my button it's going to be a custom button component and it's just going to have a button inside of it like this um there we go

10:05 button and inside the the button I don't let's just say click me for now we'll be like that okay and what we want to have happen is that every time this HTML button gets clicked we want to raise an event so whoever is using my button knows that the button was was was clicked how do we do that well the way you do that is with by defining a parameter for your compos component and that parameter should be of type event callback actually event call back of of T probably because we're going to want to pass along the mouse mouse event arcs for that uh that event okay so event callback let's finish this let's call this on click will be the name of our event and it's just a property that's getting a get has a getter and Setter

10:51 just like any other uh component parameter but because it's of type event callback we can use all of the Blazer uh patterns for passing an event call back to my button like a synchronous method an asynchronous method one that takes the the argument or one that uh that doesn't Okay so that's how you can have your own event for a component now we need to actually you know fire this event like raise it whenever the button gets clicked so let's let's take care of that so we uh we should go onto our button and add at on click and this will be on know let's call it something else on button click we already got something called on click and then we'll use our code action all right generate event handler on button click this one I think I actually want to be asynchronous I'll

11:36 show you why in just a second there we go let have a little white space okay so then in my on button click method I want to fire that onclick event that whoever's using this my button has has registered for so I take that onclick event call back and it has an invoke async method on it that I can just call and it has a couple of overloads one that doesn't take any parameters and one that takes that mouse event args parameter so I'm just going to pass the mouse event args along and then we would this is an async method so we can just return the the task okay so that's how we could do that but if we hover over the onclick attribute we can see that it actually takes an event call back of

12:21 mouse event arcs like that's the actual type of that attribute so instead of having that that extra layer we can actually just get rid of this and instead just take our event call back mouse event arcs and just pass it in just like that and so that should then uh call the uh when when when on click fires it will then call on click which will then fire our our event call back and that will call whoever registered an event handler with this component all right let's see if that actually works so let's go back to our counter and here let's go ahead and add another button up above but this is going to be my button like that and we want to register the onclick event that we just defined and we'll just wire it

13:07 up to the same increment count method that we're using for the other button okay so save that and let's go look at our app in the counter page and see what we got oh this looks like uh don watch needs to restart so let's tell it to go ahead and always restart if that happens okay all right great so now we've got two buttons we have the original button which works and then we have our our button our new button which works as well we're able to handle the uh the button click event for for our our our my button component now there's obviously a couple things that we we'd like to fix up with our my button component like how like right now it always says cook me in the text how do we make it so that we can actually actually pass some content to my button

13:53 so that it renders it inside of the HTML button well there's a way to do that in my button we can Define another parameter so another component parameter like this and this one is going to be of type render fragment so this is a special type there it is render fragment and we're also going to give this uh parameter special name it's going to be called child content and that's important because that's the that's the name that signals to Blazer that this is going to be the uh capture the content of the my button component you know the stuff me between the beginning tag and the the end tag and what a render fragment is it's like it's like capturing the chunk of Razor stuff that you put between the beginning and end tag of of my button and allows you it to

14:40 then render it someplace someplace else so I want to render this render fragment right here in our HTML button so I'm just going to use at syntax and then render the child content right in the HTML button now we've seen something similar to this before like remember when we were looking at layouts we were looking at Main layout and it had this body property if we look at the type of the body property it's also a render fragment so the the the layout component base is sort of capturing the content of each page as a render fragment so that you can render it from your from your layout so very exactly the same concept but here we're using it to capture our our child content okay so that's cool so we should now be able to go to our my button and let's actually not make it

15:26 self closing um but put some content in here now and add a closing tag and let's save that and now it says my button so we're able to capture the child content and render it inside the the the HTML button that's good um The Styling looks a little bit to be desired uh can I add like a a class attribute right here and like put some bootstrap styling you know button button success something like that let's go ahead and save that uh oh looks like we had an exception no objective type my button does not have a property matching the name class so this is Blazer being strict about saying that you know if you put an attribute on a component I expect that to be a parameter and I don't see a parameter named class on your my button

16:13 component so I'm telling you that so you can go and uh potentially address that you maybe mistyped the the parameter name but we actually want to take that HTML class attribute and just sort of pass it along to the button that we're actually rendering how can we do that well well we can do that with another parameter so let's add one more parameter to our my button component so parameter and this one is going to be of type dictionary string object and this is where we're going to just capture any additional attributes uh that are specified on the my button component so get set just like that okay additional attributes and in order to to tell Blazer that we wanted this parameter specifically to capture

16:58 that information we're going to set this capture unmatched values uh property to true on the parameter attribute okay so that means now additional attributes should have all the you know any extra stuff that we that the user decides to put on my button now we want to then render these additional attributes on the HTML button to do that there's a a razor directive that lets you do that which is the at attributes you know plural uh directive attribute and here we then just uh pass in the value of our additional attributes just like that okay and that should then Splat the attributes that were captured in that additional attributes dictionary onto the button so that now we should be able

17:44 to pass that class along let's see if that now works let's go ahead and restart all right and it's that doesn't look right did I mistype success I yeah I forgot an S there we go so now we have a blue button and a green button and we can set its content we can pass along additional attributes we can handle events awesome so we've just seen how in Blazer you can handle arbitrary uh web UI events from web elements that are in your app you can also raise events from your own components you can also pass child content to your components and render it and handle additional attributes that got uh uh attributed onto your component instances

Share

More video summaries