✅ Similar to Blazor Server
In Blazor, directives are powerful features that enable you to add additional behavior to a Razor Component on your website. With Blazor's built-in directives, you can manage various aspects of user interactions. These directives can be grouped into three types:
You can download the example code used in this topic on GitHub.
Blazor provides compiling directives that manipulate how a Razor Component is compiled. These directives include:
Directive identifier | Description |
---|---|
@inherits |
Specify the base class for a component |
@namespace |
Specify the namespace for a component |
@implements |
Specify the interface for a component |
@preservewhitespace |
Remove all redundant white spaces from an element |
@typeparam |
Specify a generic class for a component |
@layout |
Specify the layout for a component |
For instance, the @implements
directive specifies the interface for a component, as shown in the example code where the Dispose
method is implemented.
@implements IDisposable ... @code { public void Dispose() { } }
If the Dispose
method is removed, Visual Studio 2022 will emit an error during project building.
Blazor also provides DOM interaction directives used to interact with the DOM, such as
Directive identifier | Description |
---|---|
@attributes |
Attach a dictionary of attributes to the element |
@on<event> |
Attach the event handlers to the element's event |
@bind-<attribute>:<event> |
Create a 2-ways binding to an element attribute |
@key |
Set a unique identifier for an element |
@ref |
Refer the element to an C# instance |
@code |
Add C# code that defines the component's logic, state, and behavior |
For example, the @attributes
directive attaches a dictionary of attributes to an element, as demonstrated in the code.
<div @attributes="Attributes">Inspect me to see my attributes.</div> @code { Dictionary<string, object> Attributes { get; set; } = new() { { "example-string", "Blazor School" }, { "example-int", 10 }, { "example-object", new { date = DateTime.Now } } }; }
Blazor will render the HTML tag with the specified attributes:
<div example-string="Blazor School" example-int="10" example-object="{ date = 2/21/2022 8:34:57 PM }">Inspect me to see my attributes.</div>
When interacting with the DOM, you will need to handle events of an element. Although Blazor events and HTML events share the same name, they are different. The following image illustrates the difference between Blazor events and HTML events:
For example, a button with an HTML event is coded as follows:
<button type="button" onclick="alert('HTML event fired!')">HTML Event</button>
On the other hand, a button with a Blazor event is coded as follows:
<button type="button" @onclick='_ => ExampleString = "Hello Blazor School!"'>Blazor Event</button> @code { public string ExampleString { get; set; } = ""; }
This tutorial will only focus on Blazor events.
Handling HTML events with Blazor is a common task in web development. Each HTML event comes with its own data, and you can pass this event data to a C# method for further processing. Follow these steps to pass HTML event data to a C# method:
FocusEventArgs
for the onblur
event.public void OnElementBlur(FocusEventArgs args) { }
@on<event>
syntax. For example, to pass focus event data to a OnElementBlur
method:<div @onblur="OnElementBlur"></div>
Here's a table of the HTML events and their corresponding C# events:
HTML Event | C# Event | Event Group |
---|---|---|
onfocus | FocusEventArgs |
Focus |
onblur | FocusEventArgs |
Focus |
onfocusin | FocusEventArgs |
Focus |
onfocusout | FocusEventArgs |
Focus |
onmouseover | MouseEventArgs |
Mouse |
onmouseout | MouseEventArgs |
Mouse |
onmousemove | MouseEventArgs |
Mouse |
onmousedown | MouseEventArgs |
Mouse |
onmouseup | MouseEventArgs |
Mouse |
onclick | MouseEventArgs |
Mouse |
ondblclick | MouseEventArgs |
Mouse |
onwheel | WheelEventArgs |
Mouse |
onmousewheel | WheelEventArgs |
Mouse |
oncontextmenu | MouseEventArgs |
Mouse |
ondrag | DragEventArgs |
Drag |
ondragend | DragEventArgs |
Drag |
ondragenter | DragEventArgs |
Drag |
ondragleave | DragEventArgs |
Drag |
ondragover | DragEventArgs |
Drag |
ondragstart | DragEventArgs |
Drag |
ondrop | DragEventArgs |
Drag |
onkeydown | KeyboardEventArgs |
Keyboard |
onkeyup | KeyboardEventArgs |
Keyboard |
onkeypress | KeyboardEventArgs |
Keyboard |
onchange | ChangeEventArgs |
Input |
oninput | ChangeEventArgs |
Input |
oninvalid | EventArgs |
Input |
onreset | EventArgs |
Input |
onselect | EventArgs |
Input |
onselectstart | EventArgs |
Input |
onselectionchange | EventArgs |
Input |
onsubmit | EventArgs |
Input |
onbeforecopy | EventArgs |
Clipboard |
onbeforecut | EventArgs |
Clipboard |
onbeforepaste | EventArgs |
Clipboard |
oncopy | ClipboardEventArgs |
Clipboard |
oncut | ClipboardEventArgs |
Clipboard |
onpaste | ClipboardEventArgs |
Clipboard |
ontouchcancel | TouchEventArgs |
Touch |
ontouchend | TouchEventArgs |
Touch |
ontouchmove | TouchEventArgs |
Touch |
ontouchstart | TouchEventArgs |
Touch |
ontouchenter | TouchEventArgs |
Touch |
ontouchleave | TouchEventArgs |
Touch |
ongotpointercapture | PointerEventArgs |
Pointer |
onlostpointercapture | PointerEventArgs |
Pointer |
onpointercancel | PointerEventArgs |
Pointer |
onpointerdown | PointerEventArgs |
Pointer |
onpointerenter | PointerEventArgs |
Pointer |
onpointerleave | PointerEventArgs |
Pointer |
onpointermove | PointerEventArgs |
Pointer |
onpointerout | PointerEventArgs |
Pointer |
onpointerover | PointerEventArgs |
Pointer |
onpointerup | PointerEventArgs |
Pointer |
oncanplay | EventArgs |
Media |
oncanplaythrough | EventArgs |
Media |
oncuechange | EventArgs |
Media |
ondurationchange | EventArgs |
Media |
onemptied | EventArgs |
Media |
onpause | EventArgs |
Media |
onplay | EventArgs |
Media |
onplaying | EventArgs |
Media |
onratechange | EventArgs |
Media |
onseeked | EventArgs |
Media |
onseeking | EventArgs |
Media |
onstalled | EventArgs |
Media |
onstop | EventArgs |
Media |
onsuspend | EventArgs |
Media |
ontimeupdate | EventArgs |
Media |
onvolumechange | EventArgs |
Media |
onwaiting | EventArgs |
Media |
onloadstart | ProgressEventArgs |
Progress |
ontimeout | ProgressEventArgs |
Progress |
onabort | ProgressEventArgs |
Progress |
onload | ProgressEventArgs |
Progress |
onloadend | ProgressEventArgs |
Progress |
onprogress | ProgressEventArgs |
Progress |
onerror | ErrorEventArgs |
Progress |
onactivate | EventArgs |
Other |
onbeforeactivate | EventArgs |
Other |
onbeforedeactivate | EventArgs |
Other |
ondeactivate | EventArgs |
Other |
onended | EventArgs |
Other |
onfullscreenchange | EventArgs |
Other |
onfullscreenerror | EventArgs |
Other |
onloadeddata | EventArgs |
Other |
onloadedmetadata | EventArgs |
Other |
onpointerlockchange | EventArgs |
Other |
onpointerlockerror | EventArgs |
Other |
onreadystatechange | EventArgs |
Other |
onscroll | EventArgs |
Other |
ontoggle | EventArgs |
Other |
To pass parameters to a C# method from the DOM, you can use the following syntax:
<button type="button" @onclick="_ => ExampleMethodWithoutHtmlEvent(ExampleString)">Example parameterized method without HTML event</button> @code { public string ExampleString { get; set; } = ""; public void ExampleMethodWithoutHtmlEvent(string exampleString) { } }
If you need to pass HTML event data along with other parameters, you can modify the syntax as follows:
<button type="button" @onclick="(e) => ExampleMethodWithHtmlEvent(e, ExampleString)">Example parameterized method with HTML event</button> @code { public string ExampleString { get; set; } = ""; public void ExampleMethodWithHtmlEvent(MouseEventArgs eventArgs, string exampleString) { } }
preventDefault
in BlazorBy default, events in Blazor trigger their respective browser actions. To cancel these actions, you can use the preventDefault()
method in JavaScript. This method stops the default actions of the current event.
For instance, clicking on a checkbox will normally tick the checkbox. By using preventDefault()
, the checkbox will not be ticked. You can see an example of preventDefault()
in action in the following video:
Blazor makes it easy to use preventDefault()
without writing any JavaScript code. Simply add @<Blazor_event>:preventDefault
to your HTML element. For example:
<input type="checkbox" @onclick:preventDefault />
stopPropagation
in BlazorHTML elements can be nested within each other, meaning that events that occur on a child element can propagate to its parent elements. This is known as event propagation, and it can be useful in some cases. However, there may be instances where you want to prevent an event from propagating to its parent elements. To achieve this, you can use the stopPropagation()
method in JavaScript. In the following image, you can see an example of event propagation in HTML:
To prevent an event from propagating to its parent elements, you can use the stopPropagation()
method. Here's a video that demonstrates how stopPropagation()
works:
In Blazor, you can use the stopPropagation()
method without writing any JavaScript code. Simply add @<Blazor_event>:stopPropagation
to the HTML element where you want to stop event propagation. For example:
<div @onclick:stopPropagation></div>
Utility directives are a set of directives that provide additional features to your components. The following directives are part of the utility group:
Directive identifier | Description | Type |
---|---|---|
@<C#-keyword>, @{<C# Code>},@(<C# Code>) | Inject C# code to HTML template | Utilities |
@inject |
Inject an instance into a component | Utilities |
@page |
Specify the route and parameter to a component | Utilities |
@section |
Define a section, not available for Razor Component. Not commonly used in Blazor. | N/A |
@functions |
Deprecated, use @code instead |
N/A |
For example, the @page
directive is a utility directive that specifies the route for a component. Here's an example that demonstrates how @page
works:
@page "/utility" <div>The <code>@@page</code> directive helps you to navigate to this page.</div>
In the example above, the @page
directive sets the route for the current component to /utility. This means that you can access the component by navigating to localhost:XXXX/utility.