meziantou
meziantou

Reputation: 21347

How to handle dialog.onclose event in Blazor

I try to use handle the event onclose of a dialog in Blazor. I tried to use the @onclose attribute but it doesn't work.

<dialog @onclose="MyEventHandler">
</dialog>

@code {    
    async Task MyEventHandler()
    {
    }
}

This produce the following error:

Unhandled exception rendering component: InvalidCharacterError: Failed to execute 'setAttribute' on 'Element': '@onclose' is not a valid attribute name.
System.InvalidOperationException: InvalidCharacterError: Failed to execute 'setAttribute' on 'Element': '@onclose' is not a valid attribute name.
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.InvokeRenderCompletedCallsAfterUpdateDisplayTask(Task updateDisplayTask, Int32[] updatedComponents)

Is it possible to handle this event in Blazor?

Environment:

Upvotes: 3

Views: 4389

Answers (3)

Bennyboy1973
Bennyboy1973

Reputation: 4216

You're trying to put a square-shaped block through a circular hole. It's very easy to use Blazor components to toggle on-and-off. Trying to use an unpopular html tag and catch JavaScript events is not necessary.

Upvotes: 1

گلی
گلی

Reputation: 240

you can define close method and call it inside of click command:

public void Close()
    {
        ModalDisplay = "none";
        ModalClass = "";
        ShowBackdrop = false;
        StateHasChanged();
    }

and click command is as below:

<button type="button" class="close" data-dismiss="modal" aria-label="Close" @onclick="() => Close()" style="float:left;">
                        <span aria-hidden="true" class="left;">&times;</span>
                    </button>

Upvotes: 1

Quango
Quango

Reputation: 13458

There are better ways to implement dialogs as the <dialog> tag isn't widely supported (Edge, IE, Safari don't support it). Consider https://github.com/Blazored/Modal as one example.

But it can be done. You can set then open attribute to a Blazor value, and set to null when you want to hide the dialog (this removed the attribute). I've create a simple demo (link below).

https://blazorfiddle.com/s/qq3osesu

Note that this will only work on FireFox/Chrome.

Upvotes: 1

Related Questions