Ng- bootstrap модальное окно не работает в ошибочной части подписки - PullRequest
0 голосов
/ 06 марта 2020

У меня есть приложение angular со страницей входа. Когда я пытаюсь открыть модальное окно ошибки после неудачного входа в систему, я вижу только блеклый фон модального окна, но его модальное тело не отображается. Хотя, когда я реализую событие click на другом элементе с той же функциональностью, все работает как положено. Кроме того, в настоящее время на странице входа есть 2 мода, второй предназначен для успешной регистрации и работает как положено. Вот HTML часть компонента входа в систему:

    <!-- start login error modal -->
    <ng-template #loginError let-modal>
        <div class="modal-header">
            <h4 class="modal-title" id="modal-basic-title">An error occured!</h4>
            <button type="button" class="close" aria-label="Close" (click)="modal.dismiss('Cross click')">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
        <div class="modal-body">
            <div>Please, enter correct email and password.</div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-outline-dark" (click)="modal.close('Save click')">OK</button>
        </div>
    </ng-template>
    <!-- end login error modal -->

//everything works when you click on this element
<span class="footer-text" (click)="openError(loginError)">&nbsp;Policy</span>

//second modal window(works fine)
    <ng-template #content let-modal>
        <div class="modal-header">
            <h4 class="modal-title" id="modal-basic-title">Congratulations!</h4>
            <button type="button" class="close" aria-label="Close" (click)="modal.dismiss('Cross click')">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
        <div class="modal-body">
            <div>You have successfully registered on our platform! Please log in using your username and password</div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-outline-dark" (click)="modal.close('Save click')">OK</button>
        </div>
    </ng-template>

Соответствующая часть компонента TS:

//onLogin function that shows just faded background when error occured
onLogin(loginError) {
  // activating submission flag
  this.submitted = true;

  // stop here if form is invalid
  if (this.loginForm.invalid) {
    return;
  }
  // activating loading flag
  this.loading = true;

  this.authenticationService.login(this.f.username.value, this.f.password.value)
    .pipe(first())
    // subscribing after successful login
    .subscribe(
      data => {
        //redirecting on "profile" page
        let id = data.id;
        this.router.navigate([`/user/${id}`]);
      },
      // error handling
      error => {
        this.loading = false;
        this.modalService.open(loginError);
      });
}

//function that works as expected
openError(loginError) {
  this.modalService.open(loginError)
}

//onRegister function that shows second modal as expected
onRegister(content) {
  // activating submission flag for register function
  this.submitReg = true;

  if (!this.registerForm.valid) {
    return
  }

  this.authenticationService
  // sending values to auth service function
    .signin(this.r.email.value, this.r.password.value, this.r.first_name.value, this.r.last_name.value, this.gender, `${this.year}-${this.month}-${this.day}`, true)
    .pipe(first())
    .subscribe(
      data => {
        this.submitReg = false;
        //open modal
        this.modalService.open(content);
        // reset register form
        this.registerForm.reset();
      },
      error => {
        this.loading = false;
      });
}

Я пытался открыть второй модал из функции onRegister в onLogin, но это не помогло или. Спасибо за вашу помощь, любые советы будут оценены.

1 Ответ

0 голосов
/ 06 марта 2020

Я рекомендую создать два отдельных компонента Angular для двух модальных типов. Когда есть два компонента, они могут быть добавлены к желаемому модулю (наиболее вероятно, к app.module.ts) как компонент ввода в массиве entryComponents в декораторе модуля. entryComponents используется для динамически создаваемых компонентов, таких как модал ng- bootstrap.

Хороший пример кода можно найти здесь: https://stackblitz.com/edit/ng-bootstrap-modals

И учебник для этого здесь: https://medium.com/@izzatnadiri / как передать данные для получения и получения от ng- bootstrap -modals-916f2ad5d66e

...