在一个Angular2应用程序中,我有一个组件(比方说EditForm
),它代表了一个表单,通过它我可以编辑我的模型的某个实例(让我们说modelInstance
)。
有一个页面包含EditForm
组件列表,允许用户在同一页面中查看并可能编辑多个modelInstance
。
一旦用户退出EditForm
组件(即焦点移动到组件外的某处),我想激发一种方法来检查用户想要离开的EditForm
组件中包含的数据输入的完整性和正确性(类似于blur
事件但适用于整个组件)。
用例确实预见到页面级别只有一个提交按钮,但我想在任何时候放弃某个EditForm
时实现检查逻辑。
我目前正在努力找到一种优雅的方式来做我需要的东西,我担心我会忽略在我面前的简单而整洁的解决方案。任何帮助,将不胜感激。
提前致谢
你可以在你的组件上听focusout
,然后通过迭代它的父项来检查document.activeElement
是否在你的表单之外,直到你到达当前组件,然后它在里面,或<body>
,然后它在外面。
导出类MyForm {
@HostListener('focusout', ['$event'])
focusout(event) {
console.log('focusout', event);
// some delay required otherwise `document.activeElement` is not yet set
setTimeout(() => {
console.log('new focus', document.activeElement);
});
}
model1 = 'default1';
model2 = 'default2';
}
Plunker example(不包含内/外支票)
为什么不用ngSubmit()放置组件检查方法,然后决定下一步做什么,甚至停止提交表单。
<form *ngIf="active" (ngSubmit)="onSubmit()" #heroForm="ngForm">
对于Angular2,每个表单元素的数据验证都可以与它一起绑定。
对于Angular2,您可能需要使用ngControl
https://angular.io/docs/js/latest/api/common/NgControl-class.html
在评论中通知的上一个链接已中断。新链接:https://angular.io/api/forms/NgControl
正如官方文档中所述
使用ngControl跟踪表单控件的更改状态和有效性
例如
this.username = new Control('Default value', Validators.required, UsernameValidator.checkIfAvailable);
可以使用“ngControl”指令在HTML中使用
<input required type=”text” ngControl=”username” />
一个完整的教程,带有angular2方式的表单管理示例:https://angular.io/docs/ts/latest/guide/forms.html
在评论中通知的上一个链接已中断。新链接:https://angular.io/guide/forms
检查doc(上面的链接)中的“实例”可以作为测试场景的操场。