首页 > 解决方案 > 从子内部组件关闭模态

问题描述

我有一个标题组件,其中包含一个在单击时触发的模式窗口

<a (click)="open(content)" class="in">Sign in</a>
<ng-template #content let-modal>
  <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">
    <app-login></app-login>
  </div>
</ng-template>

我有一个带有表单和按钮的子组件(app-login):

<button [disabled]="loading" class="btn btn-primary">
    <span *ngIf="loading" class="spinner-border spinner-border-sm mr-1"></span>
    Login
</button>

我的问题是,一旦我登录,模式仍然打开。我正在为这个应用程序使用 ng bootstrap。

这是 LoginComponent ts 文件。此类允许构建和验证表单的字段并进行重定向:

export class LoginComponent implements OnInit {
   // ... variables declarations

  constructor(
    private formBuilder: FormBuilder,
    private route: ActivatedRoute,
    private router: Router,
    private authenticationService: AuthenticationService
  ) {
    if (this.authenticationService.currentUserValue) {
      this.router.navigate(['/']);
    }
  }

  get f() { return this.loginForm.controls; }

  onSubmit() {
    ...
  }
}

这里是我的标头组件,我的模态在其中打开。它包含 2 种方法:

export class HeaderComponent implements OnInit {
   // ... variables declarations    
  constructor(private modalService: NgbModal) {}

  open(content) {
    this.modalService.open(content, {ariaLabelledBy: 'modal-basic-title'}).result.then((result) => {
      this.closeResult = `Closed with: ${result}`;
    }, (reason) => {
      this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
    });
  }    
  private getDismissReason(reason: any): string {
    if (reason === ModalDismissReasons.ESC) {
      return 'by pressing ESC';
    } ...
  }
}

标签: angular

解决方案


在子组件中,处理 ng-bootstrap (close) 事件:

(close)="onModalClose()"

并在打字稿中发出该事件:

close: EventEmitter<void> = new EventEmitter<void>();

onModalClose(): void {
  this.close.emit();
}

然后在你的父母中处理孩子的关闭事件:

(close)="onClose()"

并在您的打字稿中隐藏模式:

onClose(): void {
  this.showModal = false;
}

其中 showModal 用于确定模态是否应该打开。


推荐阅读