以下是一个示例代码,展示如何在模态窗口中提交 Angular 表单:
import { Component, ViewChild } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent {
@ViewChild('myModal') myModal: any; // 获取模态窗口的引用
constructor(private modalService: NgbModal) {}
openModal() {
this.modalService.open(this.myModal, { ariaLabelledBy: 'modal-basic-title' })
.result.then((result) => {
// 处理模态窗口关闭后的结果
if (result === 'submit') {
// 执行表单提交操作
this.submitForm();
}
}, (reason) => {
// 处理模态窗口关闭的原因
});
}
submitForm() {
// 执行表单提交操作
// ...
}
}
模态窗口标题
在这个示例中,我们使用了 ng-bootstrap 库来创建模态窗口。首先,我们在组件类中引入 NgbModal 服务,并将其注入到构造函数中。然后,我们使用 ViewChild 装饰器来获取模态窗口的引用,这样我们就可以在 openModal 方法中使用它。
在 openModal 方法中,我们调用 modalService 的 open 方法来打开模态窗口,并传入模板引用和一些选项。在结果回调函数中,我们检查关闭模态窗口的结果,如果是 'submit',则调用 submitForm 方法来执行表单提交操作。
在模态窗口的模板中,我们使用 ng-template 来定义模态窗口的内容。在表单上,我们使用了 ngSubmit 事件来捕获表单的提交动作,并在事件处理程序中调用 modal.close 方法来关闭模态窗口并传递结果。在按钮上,我们也使用了 modal.close 方法来关闭模态窗口,并传递不同的结果值('submit' 或 'cancel')。
通过以上代码示例,按下回车键后,在模态窗口中提交 Angular 表单就可以实现了。
下一篇:按下回车键后,在输入旁边打印输出