[英]Angular2 - How to notify that a Component is loosing focus
在Angular2應用程序中,我有一個組件(比如說EditForm
),它代表一個表單,通過它我可以編輯我的模型的某個實例(比如說modelInstance
)。
有一個頁面包含EditForm
組件列表,以允許用戶在同一頁面中查看並可能編輯多個modelInstance
。
一旦用戶退出EditForm
組件(即焦點移動到組件外的某處),我想激發一種方法,檢查用戶想要離開的EditForm
組件中包含的數據輸入的完整性和正確性(類似blur
事件)但適用於整個組件)。
用例確實只預見了頁面級別的一個提交按鈕,但是我希望在放棄某個EditForm
任何時候實現檢查邏輯。
我目前正在努力找到一種優雅的方式來做我需要的東西,我擔心我會忽略在我面前的簡單而整潔的解決方案。 任何幫助,將不勝感激。
提前致謝
為什么不用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(上面的鏈接)中的“實例”可以作為測試場景的操場。
您可以監聽組件的focusout
,然后通過迭代其父項直到您到達當前組件,然后它在內部或<body>
,然后它在外面來檢查document.activeElement
是否在表單之外。
導出類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示例 (不包含內部/外部檢查)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.