[英]how to get angular2 formcontrol parent
如何在控件的嵌套表單組中獲取父表單組。 在驗證控件時,我需要一個同級控件值。 這兩個控件都是 formgroup 的一部分,formgroup 是 formArray 的一部分。 我知道我們有 root,它給出了根元素。 如何獲得給定表單控件的直接父級。
您可以訪問給定的父FormControl
與.parent
你會用同樣的方式.root
。
我有同樣的問題。 我們有一個這樣的嵌套表單組:
FormGroup1:
- FormControl1
- FormControl2
- FormGroup2
- FormControl3
- FormControl4
因此,在 FormGroup2.FormControl3 的自定義驗證器中,您可以像這樣找到 FormGroup1 的根:
export class CustomValidator {
static FormControl3Valid() {
return function (input: FormControl) {
if (!input.root || !input.parent) {
return null;
}
const root = input.root as FormGroup;
if (root.get('FormControl1').value === 'someValue1' &&
root.get('FormGroup2').get('FormControl4').value === 'someValue2') {
return { 'required': true };
}
return null;
};
}
}
請記住,這段代碼有很大的不同:
if (!input.root || !input.parent) {
return null;
}
在導航到 root 或 parent 之前,您必須檢查 FormGroups 是否已創建。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.