Reputation:
I am trying to make a Razor component that removes itself from the page after 3 seconds, after its added to 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
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