title
stringlengths 3
46
| content
stringlengths 0
1.6k
|
---|---|
19:420
|
Both HTML tags and Blazor components use attributes/parameters to get input. HTML tags provide output to the remainder of the page through events, and Blazor allows C# functions to be attached to HTML on{event name} attributes. The syntax is shown in the Pages->Counter.razor component:
|
19:421
|
<p role=`status`>Current count: @currentCount</p>
|
19:422
|
<button class=`btn btn-primary` @onclick=`IncrementCount`>Click me</button>
|
19:423
|
@code {
|
19:424
|
private int currentCount = 0;
|
19:425
|
private void IncrementCount()
|
19:426
|
{
|
19:427
|
currentCount++;
|
19:428
|
}
|
19:429
|
}
|
19:430
| |
19:431
|
The function can also be passed inline as a lambda. Moreover, it accepts the C# equivalent of the usual event argument. The Further reading section contains a link to the Blazor official documentation page that lists all supported events and their arguments.
|
19:432
|
Since Blazor components are designed as enhanced versions of HTML elements—with added capabilities—they can also have events. However, unlike standard HTML elements, both the features and implementations of these events in Blazor components are defined by the developer.
|
19:433
|
Blazor events enable components to return output, too. Component events are defined as parameters whose type is either EventCallBack or EventCallBack<T>. EventCallBack is the type of component event with no arguments while EventCallBack<T> is the type of component event with an argument of type T. In order to trigger an event, say MyEvent, the component calls:
|
19:434
|
await MyEvent.InvokeAsync()
|
19:435
| |
19:436
|
or
|
19:437
|
await MyIntEvent.InvokeAsync(arg)
|
19:438
| |
19:439
|
These calls execute the handlers bound to the events or do nothing if no handler has been bound.
|
19:440
|
Once defined, component events can be used exactly in the same way as HTML element events, the only difference being that there is no need to prefix the event name with an @, since @ in HTML events is needed to distinguish between the HTML attribute and the Blazor-added parameter with the same name:
|
19:441
|
[Parameter]
|
19:442
|
publicEventCallback MyEvent {get; set;}
|
19:443
|
[Parameter]
|
19:444
|
publicEventCallback<int> MyIntEvent {get; set;}
|
19:445
|
...
|
19:446
|
...
|
19:447
|
<ExampleComponent
|
19:448
|
MyEvent=`() => ...`
|
19:449
|
MyIntEvent = `(i) =>...` />
|
19:450
| |
19:451
|
Actually, HTML element events are also EventCallBack<T> events. That is why both event types behave in exactly the same way. EventCallBack and EventCallBack<T> are structs, not delegates, since they contain a delegate, together with a pointer to the entity that must be notified that the event has been triggered. Formally, this entity is represented by a Microsoft.AspNetCore.Components.IHandleEvent interface. Needless to say, all components implement this interface. The notification informs IHandleEvent that a state change took place. State changes play a fundamental role in the way Blazor updates the page HTML. We will analyze them in detail in the next subsection.
|
19:452
|
For HTML elements, Blazor also provides the possibility to stop the event’s default action and the event bubbling by adding the :preventDefault and :stopPropagation directives to the attribute that specifies the event, like in these examples:
|
19:453
|
@onkeypress=`KeyHandler` @onkeypress:preventDefault=`true`
|
19:454
|
@onkeypress:stopPropagation =`true`
|
19:455
| |
19:456
|
Bindings
|
19:457
|
Often, a component parameter value must be kept synchronized with an external variable, property, or field. The typical application of this kind of synchronization is an object property being edited in an input component or HTML tag. Whenever the user changes the input value, the object property must be updated coherently, and vice versa. The object property value must be copied into the component as soon as the component is rendered so that the user can edit it.
|
19:458
|
Similar scenarios are handled by parameter-event pairs. More specifically, from one side, the property is copied in the input component parameter. From the other side, each time the input changes value, a component event that updates the property is triggered. This way, property and input values are kept synchronized.
|
19:459
|
This scenario is so common and useful that Blazor has a specific syntax for simultaneously defining the event and copying the property value into the parameter. This simplified syntax requires that the event has the same name as the parameter involved in the interaction but with a Changed postfix.
|
19:460
|
Suppose, for instance, that a component has a Value parameter. Then, the corresponding event must be ValueChanged. Moreover, each time the user changes the component value, the component must invoke the ValueChanged event by calling await ValueChanged.InvokeAsync(arg). With this in place, a property called MyObject.MyProperty can be synchronized with the Value property with the syntax shown here:
|
19:461
|
<MyComponent @bind-Value=`MyObject.MyProperty`/>
|
19:462
| |
19:463
|
The preceding syntax is called binding. Blazor takes care of automatically attaching an event handler that updates the MyObject.MyProperty property to the ValueChanged event.
|
19:464
|
Bindings of HTML elements work in a similar way, but since the developer can’t decide the names of parameters and events, a slightly different convention must be used. First of all, there is no need to specify the parameter name in the binding, since it is always the HTML input value attribute. Therefore, the binding is written simply as @bind=`object.MyProperty`. By default, the object property is updated on the change event, but you can specify a different event by adding the @bind-event: @bind-event=`oninput` attribute.
|
19:465
|
Moreover, bindings of HTML inputs try to automatically convert the input string into the target type. If the conversion fails, the input reverts to its initial value. This behavior is quite primitive since, in the event of errors, no error message is provided to the user, and the culture settings are not taken into account properly (HTML5 inputs use invariant culture but text input must use the current culture). We advise binding inputs only to string target types. Blazor has specific components for handling dates and numbers that should be used whenever the target type is not a string. We will describe these components in the Blazor forms and validation section.
|
19:466
|
In order to familiarize ourselves with events, let’s write a component that synchronizes the content of an input-type text when the user clicks a confirmation button. Let’s right-click on the Layout folder and add a new ConfirmedText.razor component. Then replace its code with this:
|
19:467
|
<input type=`text` @bind=`Value` @attributes=`AdditionalAttributes`/>
|
19:468
|
<button class=`btn btn-secondary` @onclick=`Confirmed`>@ButtonText</button>
|
19:469
|
@code {
|
19:470
|
[Parameter(CaptureUnmatchedValues = true)]
|
19:471
|
public Dictionary<string, object> AdditionalAttributes { get; set; }
|
19:472
|
[Parameter]
|
19:473
|
public string Value {get; set;}
|
19:474
|
[Parameter]
|
19:475
|
public EventCallback<string> ValueChanged { get; set; }
|
19:476
|
[Parameter]
|
19:477
|
public string ButtonText { get; set; }
|
19:478
|
async Task Confirmed()
|
19:479
|
{
|
19:480
|
await ValueChanged.InvokeAsync(Value);
|
19:481
|
}
|
19:482
|
}
|
19:483
| |
19:484
|
The ConfirmedText component exploits the button-click event to trigger the ValueChanged event. Moreover, the component uses @bind to synchronize its Value parameter with the HTML input. It is worth pointing out that the component uses CaptureUnmatchedValues to forward all HTML attributes applied to its tag to the HTML input. This way, users of the ConfirmedText component can style the input field by simply adding class and/or style attributes to the component tag.
|
19:485
|
Now, let’s use this component in the Pages->Index.razor page by placing the following code at the end of Home.razor:
|
19:486
|
<ConfirmedText @bind-Value=`textValue` ButtonText=`Confirm` />
|
19:487
|
<p>
|
19:488
|
Confirmed value is: @textValue
|
19:489
|
</p>
|
19:490
|
@code{
|
19:491
|
private string textValue = null;
|
19:492
|
}
|
19:493
| |
19:494
|
If you run the project and play with the input and its Confirm button, you will see that each time the Confirm button is clicked, not only are the input values copied in the textValue page property but also the content of the paragraph that is behind the component is coherently updated.
|
19:495
|
We explicitly synchronized textValue with the component with @bind-Value, but what takes care of keeping textValue synchronized with the content of the paragraph? The answer can be found in the next subsection.
|
19:496
|
How Blazor updates HTML
|
19:497
|
When we write the content of a variable, property, or field in Razor markup with something like @model.property, Blazor not only renders the actual value of the variable, property, or field when the component is rendered but tries also to update the HTML each time that this value changes, with a process called change detection. Change detection is a feature of all the main SPA frameworks, but the way Blazor implements it is very simple and elegant.
|
19:498
|
The basic idea is that once all HTML has been rendered, changes may occur only because of code executed inside of events. That is why EventCallBack and EventCallBack<T> contain a reference to an IHandleEvent. When a component binds a handler to an event, the Razor compiler creates an EventCallBack or EventCallBack<T>, passing its struct constructor the function bound to the event, and the component where the function was defined (IHandleEvent).
|
19:499
|
Once the code of the handler has been executed, the Blazor runtime is notified that the IHandleEvent might have changed. In fact, the handler code can only change the values of variables, properties, or fields of the component where the handler was defined. In turn, this triggers a change detection process rooted in the component. Blazor verifies which variables, properties, or fields used in the component Razor markup changed and updates the associated HTML.
|
19:500
|
If a changed variable, property, or field is an input parameter of another component, then the HTML generated by that component might also need updates. Accordingly, another change detection process rooted in that component is recursively triggered.
|
19:501
|
The algorithm sketched previously discovers all relevant changes only if the following conditions are met:
|
19:502
| |
19:503
|
No component references data structures belonging to other components in an event handler.
|
19:504
|
All inputs to a component arrive through its parameters and not through method calls or other public members.
|
19:505
| |
19:506
|
When there is a change that is not detected because of the failure of one of the preceding conditions, the developer must manually declare the possible change of the component. This can be done by calling the StateHasChanged() component method. Since this call might result in changes to the page’s HTML, its execution cannot take place asynchronously but must be queued in the HTML page’s UI thread. This is done by passing the function to be executed to the InvokeAsync component method.
|
19:507
|
Summing up, the instruction to execute is await InvokeAsync(StateHasChanged).
|
19:508
|
The next subsection concludes the description of components with an analysis of their lifecycle and the associated lifecycle methods.
|
19:509
|
Component lifecycle
|
19:510
|
Each component lifecycle event has an associated method. Some methods have both synchronous and asynchronous versions, some have just an asynchronous version, and some others have just a synchronous version.
|
19:511
|
The component lifecycle starts with parameters passed to the component being copied in the associated component properties. You can customize this step by overriding the following method:
|
19:512
|
public override async Task SetParametersAsync(ParameterView parameters)
|
19:513
|
{
|
19:514
|
await ...
|
19:515
|
await base.SetParametersAsync(parameters);
|
19:516
|
}
|
19:517
| |
19:518
|
Typically, customization consists of the modification of additional data structures, so the base method is called to also perform the default action of copying parameters in the associated properties.
|
19:519
|
After that, there is the component initialization that is associated with the two methods:
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.