angular - 从子内部组件关闭模态
问题描述
我有一个标题组件,其中包含一个在单击时触发的模式窗口
<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">×</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';
} ...
}
}
解决方案
在子组件中,处理 ng-bootstrap (close) 事件:
(close)="onModalClose()"
并在打字稿中发出该事件:
close: EventEmitter<void> = new EventEmitter<void>();
onModalClose(): void {
this.close.emit();
}
然后在你的父母中处理孩子的关闭事件:
(close)="onClose()"
并在您的打字稿中隐藏模式:
onClose(): void {
this.showModal = false;
}
其中 showModal 用于确定模态是否应该打开。
推荐阅读
- pyspark - pyspark:计算每个不同值的出现次数
- makefile - 配置 makefile 以在链接器阶段使用调试信息进行编译
- html - base64 中的图像忽略 EXIF 方向
- android-studio - AGP 3.3 和 Gradle 5.0 针对已过时且将于 2019 年底删除的变体发出警告
- openssl - 使用boringssl库时出现分段错误
- excel - 使用宏更改多个 excel 文件的列的数据类型
- cobol - 如何将最后一位数字移动到cobol中数字的第一位
- javascript - 将 SurveyJS 数据推送到 MongoDB
- android - Kivy & Buildozer: How to play audio while Android Application is loading?
- php - 如何使用 PHP 从 URL 下载多个图像并将它们保存在我的文件夹中?