Search code examples
blazorblazor-webassemblymatblazor

Blazor: Close MatBlazor PopUp Dialog box after Login success in Child Component


I have a Login.razor the page where all the action happens.

@page "/login"
@inject IAuthService AuthService
@inject NavigationManager NavigationManager

@if (ShowErrors)
{
    <div class="alert alert-danger" role="alert">
        <p>@Error</p>
    </div>
}

<div class="card">
    <div class="card-body">
        <EditForm Model="loginModel" OnValidSubmit="HandleLogin">
            <DataAnnotationsValidator />
            <ValidationSummary />

            <div class="form-group">
                <label for="email">Email address</label>
                <InputText Id="email" Class="form-control" @bind-Value="loginModel.Email" />
                <ValidationMessage For="@(() => loginModel.Email)" />
            </div>
            <div class="form-group">
                <label for="password">Password</label>
                <InputText Id="password" type="password" Class="form-control" @bind-Value="loginModel.Password" />
                <ValidationMessage For="@(() => loginModel.Password)" />
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
        </EditForm>
    </div>
</div>

@code {

    private LoginModel loginModel = new LoginModel();
    private bool ShowErrors;
    private string Error = "";

    private async Task HandleLogin()
    {
        ShowErrors = false;

        var result = await AuthService.Login(loginModel);

        if (result.Successful)
        {
            NavigationManager.NavigateTo("/");
        }
        else
        {
            Error = result.Error;
            ShowErrors = true;
        }
    }
}

And my MainLayout.razor contains the Matblazor dialog popup.

<MatDialog @bind-IsOpen="@signInOpen">
    <MatTabGroup>
        <MatTab Label="SIGN IN">
            <BlazorCom.Client.Pages.Login />
        </MatTab>
    </MatTabGroup>
</MatDialog>

@code
{
    public bool signInOpen = false;

    void OpenDialog()
    {
        signInOpen = true;
    }
}

When I log in using this dialog box the box doesn't close on its own as I have no idea how to do that. Now I want to close the Popup dialog box after a successful login. Can anyone help me with that?


Solution

  • Set signInOpen to false and the dialog will close.

    Edit: If you need to set it from the outside add a method Close like this:

    @code {
    
    public void CloseDialog() {
      signInOpen=false;
      StateHasChanged();
    }
    

    Then in Login.razor you can call the CloseDialog() function in the @onclick event of the submit button.