Modal close and form value reset not working in Angular

Arthi picture Arthi · Aug 29, 2018 · Viewed 7.1k times · Source

Crossing with many existing questions related to my question, I post this. So don't comment this as duplicate and send duplicate answers my scenario is a little bit different. All solutions are related to javascript or jquery. But I want in Angular.

I am using mdBootstrap, providing only the CDN link in index.html not installing it. I have a popup with tabs for login & Register. The problem is after entering credentials and click login modal is not closing(I don't want to put data-dismiss="modal") as it closes the modal without doing login functionality. I want both functions to be done, validating the credentials if it is invalid, I want the modal is in open saying error message. If it is valid then only modal to be closed.

The second thing I want to reset the modal form values even when I click anywhere outside the modal and reopen the modal. For example, if I have two input fields like username and password, I entered only the username leaving the password blank and click outside and reopen the modal, my modal opened with the entered username value. I want to get rid of these problems.

Anyone help me to fix these issues. Thanks in Advance.

Log-Reg.component.html

<div class="modal fade" id="modalLoginRegisterForm" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-body">
        //tabs for login & Register
        <div class="tab-content py-0">
          <div class="tab-pane fade in show active" id="modalLoginTab" role="tabpanel">
            <form #loginForm="ngForm">
              <div class="md-form">
                <input required [(ngModel)]="username" type="email" id="loginEmail" name="Username" class="form-control validate">
                <label for="loginEmail">Enter your email address</label>
              </div>
              <div class="md-form">
                <input required [(ngModel)]="password" type="password" id="loginPassword" name="Password" class="form-control validate">
                <label for="loginPassword">Enter your password</label>
              </div>
              <div *ngIf="isLoginError" class="alert alert-danger">Incorrect Credentials</div>
              <button type="button" [disabled]=!loginForm.valid class="btn btn-primary" (click)="onLogin()">Login</button>
            </form>
          </div>
          //Form for Register
        </div>
      </div>
    </div>
  </div>
</div>

Log-Reg.component.ts

@ViewChild('loginForm') public userLoginForm : NgForm;

onLogin(){
//some function for login validation\
this.userLoginForm.reset();
}

Answer

Krishna Rathore picture Krishna Rathore · Aug 29, 2018

Try this.

this.userLoginForm.form.reset()

or

this.userLoginForm.resetForm()