0

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();
    }
}
1
  • 1
    Sounds like a simple Blazor if statement would work to remove the div and paragraph from the DOM here, or is there a reason you're trying to remove the component itself? Which, btw, I don't believe is possible to do from the inside the component itself - you would have to do this at the parent level where this component's calling-markup exists. Commented Apr 27, 2021 at 13:07

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.