user13028588
user13028588

Reputation:

How to Remove Element / Component from BlazorWebassambly

I am trying to make a Razor component that removes itself from the page after 3 seconds, after its added to the page.

  1. I will click on a button
  2. Than the Component will be added to the current page
  3. After 3 seconds the Component removes itselfrom the page
<**div @ref="messageRef" style="position: absolute; margin: 0 auto; background-color: red; width: 200px; height: 80px;">**

    <p>Message.....</p>
</div>

@code {
    ElementReference messageRef;

    private MessageComponent thisMsg;
    protected override async Task OnInitializedAsync()
    {
        await JSRuntime.InvokeVoidAsync("MessageComponent.Remove()", messageRef); 
        StateHasChanged();
    }
}

Upvotes: 0

Views: 3686

Answers (1)

Eric King
Eric King

Reputation: 11734

As JeremyW mentions in his comment, this can be done with an @if statement in the body of the page that holds the content. Using the Blazor template app as an example, it might look something like this:

@page "/"

<h1>Hello, world!</h1>

Welcome to your new app.

@if (displayPrompt)
{
    <SurveyPrompt Title="How is Blazor working for you?" />
}

@code {
    private bool displayPrompt;

    protected override void OnInitialized()
    {
        displayPrompt = true;
        HideMessageAfterDelay();
        base.OnInitialized();
    }

    private async void HideMessageAfterDelay()
    {
        await Task.Delay(3000);
        displayPrompt = false;
        StateHasChanged();
    }
}

When displayPrompt evaluates to true, the prompt is added to the DOM. When is evaluates to false, it's removed from the DOM.

If you need the message component to handle this itself, then just put the equivalent code inside the component itself instead of the page.

Upvotes: 2

Related Questions