-
-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathElementRefComponent.razor
More file actions
36 lines (31 loc) · 1.24 KB
/
ElementRefComponent.razor
File metadata and controls
36 lines (31 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
@inject IJSRuntime JSRuntime
<h1>Element capture</h1>
<p>
This shows how an element reference may be captured as a field value using 'ref' syntax and then
passed to JavaScript code, which receives the actual DOM element instance.
</p>
<p>
Note that 'ref' syntax is primarily intended for use with JavaScript interop. It is <strong>not</strong>
recommended to use it for mutating the DOM routinely. All DOM construction and mutation that can be
done declaratively is better, as it automatically happens at the correct time and with minimal diffs.
Plus, whenever you use 'ref', you will not be able to run the same code during unit tests or
server-side rendering. So it's always better to prefer declarative UI construction when possible.
</p>
@if (_toggleCapturedElementPresence)
{
<input id="capturedElement" @ref="_myInput" />
}
<button @onclick="MakeInteropCall">Click me</button>
<label>
<input type="checkbox" @bind="_toggleCapturedElementPresence" />
Toggle input
</label>
@code {
int _count = 0;
bool _toggleCapturedElementPresence = true;
ElementReference _myInput;
async Task MakeInteropCall()
{
await JSRuntime.InvokeVoidAsync("setElementValue", _myInput, $"Clicks: {++_count}");
}
}