首页 > 解决方案 > How to open a modal component from inside of another modal component without having a circular dependency?

问题描述

I have two ngx-bootstrap modals created as a standalone components (not with template variables) - Login modal and Register modal. Each of the modals are have separate components which are located in my shared module and can be called from other modules. But the thing is that there is an option these modals to call each other - you can click a button from the login modal which has to bring you the Register modal and vice versa. When I try doing this using the BsModalService I get circular dependency errors since I have imported the login component in the register component and the register component in the login component.

I've tried to put this modal switching logic in a service with the hope that I won't get a circular dependency but it didn't help.

   import { Component, OnInit } from '@angular/core';
   import { FormGroup, FormBuilder, Validators } from '@angular/forms';
   import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal';
   import { UserService } from 'src/app/core/services';
   import { User } from 'src/app/core';
   import { RegisterModalComponent } from '../register-modal/register-modal.component';

@Component({
  selector: 'app-login-modal',
  templateUrl: './login-modal.component.html',
  styleUrls: ['./login-modal.component.css']
})
export class LoginModalComponent implements OnInit {

  loginForm: FormGroup = this.fb.group({
      // form definition
  });

  constructor(
    public loginModalRef: BsModalRef,
    private fb: FormBuilder,
    private router: Router,
    private user: UserService,
    private modalService: BsModalService
  ) { }

  ngOnInit() {
  }

  onSubmit() {
     // form submit code ...
    // hide the current modal
    this.loginModalRef.hide();
  }

  openRegisterModal() {
    // hide the current modal
    this.loginModalRef.hide();
    // open the new modal
    this.modalService.show(RegisterModalComponent, {
      animated: true,
      class: 'modal-lg'
    });
  }
}

I have included only the code from the login modal since the situation on the other side is similar.

标签: modal-dialogbootstrap-modalngx-bootstrap

解决方案


顺便提一下,作为一种临时解决方案,我只是制作了一个模态组件来作为模态组件,我将登录和注册组件重构为像常规组件一样,因此我可以将它们包含在模态组件中并使用 ngIf 切换它们,具体取决于我调用模态的参数。


推荐阅读