简体   繁体   中英

How can I tell if an element reference does exist in blazor

If an element is hidden in first render (for example the element is in an if statement scope which has evaluated as false, so won't get rendered), and some event makes it appear (if statement evaluate as true) the inner element reference gets updated after render. This works absolutely fine.

But in case the opposite event flow (first is true, than gets hidden by some event), the element reference does not get updated after render, still shows the original id instead of null or empty string. In this case if I call JsInterop with that element reference, it would give an error that element does not exists (which is obviously true). The problem is that the element reference still has the former id, it didn't get changed after render.

The question is how can I tell if an element is visible (rendered, existing) or not?

Blazor does not destroy the ElementReference object. It is persisted for further usage. But it is always populated with new data; that is the insurrected ElementReference object gets a new id. Thus you can always compare two consecutive values of the id

You can set an element reference to its default value:

elementRef = default(ElementReference);

This is equivalent to setting a reference object to null.

And you can check weather an element reference does exist like this;

if (EqualityComparer<ElementReference>.Default.Equals(elementRef, 
                                             default(ElementReference)))
 {
     // Does not exist...      
 }
 

Play with this code, and see that whatever you've said is wrong, unless I didn't get you.

@page "/"


@if (display)
{
    <div @ref="elementRef">Welcome to your new app.</div>
}

<button @onclick="@(() => display = !display )">Toggle</button>
<button @onclick="ConsoleWrite">Console</button>
@code{ 
    private bool display = true;
    ElementReference elementRef;

    private void ConsoleWrite()
    {
               
        Console.WriteLine(elementRef.Id);

        if (!EqualityComparer<ElementReference>.Default.Equals(elementRef, default(ElementReference)))
        {
            Console.WriteLine("return false");
        }

        // Set the element reference to its default value
        elementRef = default(ElementReference);

        if (EqualityComparer<ElementReference>.Default.Equals(elementRef, default(ElementReference)))
        {
            Console.WriteLine("Return true after being set to its default value");
        }

        Console.WriteLine("elementRef.Id is null now" + elementRef.Id);

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM