2016-11-28 42 views
0

我想在angular2中創建一個驗證器,我需要檢查另一個表單域的值。我嘗試過兩種場景,我試圖做到這一點。Angular2驗證器依賴於另一個表單域

方案1,表單域看起來是這樣的:

Form = this._fb.group({ 
     ansat: ['', [<any>Validators.required]], 
     helbred: ['', this.someValidator('ansat')], 
    }); 

我有上述兩個領域,我希望能夠檢查「安薩特」的值的驗證功能「someValidator」。 someValidator看起來是這樣的:

someValidator(key: string) { 
    return (group: FormGroup) => { 
     console.log(group); 
     console.log(group.controls[key].value); 
    } 
    } 

在我的功能,工作組包括所有爲我formgroup正確的信息,但「控制」是不確定的,這意味着我不能去的「安薩特值

方案。 2,表單域看起來是這樣的:

this.myForm = this._fb.group({ 
     ansat: ['', [<any>Validators.required]], 
     helbred: ['', c => Validators.compose([ 
      this.someValidator(c, 
       group => group.controls['ansat'].value === 0 
      ), 
     ])] 
    }); 

這是我someValidator功能:

conditional(c, conditional) { 
    console.log(conditional); 
    console.log(c); 

    if(c.parent != undefined || c._parent != undefined){ 
     if(c._parent.controls['ansat'].value === 0){ 
     console.log(c._parent.controls['ansat'].value); 
     } 
    } 
    return null; 
    } 

在這種情況下,控件「c」具有正確的信息,並且包含一個父組,它是分配給它的組,但我無法訪問它以嘗試將它的兄弟放在同一組中。

而在條件參數的情況下,我嘗試通過一個我無法讓它工作的函數來發送該組。

問題:我希望能夠訪問我稱之爲「helbred」的驗證程序中的「ansat」值。我該怎麼做呢?

任何幫助,非常感謝!

回答

1

看一看this猛擊。 你在正確的軌道上,你必須在helbred控件的驗證器中傳遞實際的ansat控件,而不是僅傳遞ansat控件的值。

ansat: AbstractControl = new FormControl('', Validators.required); 
helbred: AbstractControl = new FormControl('', Validators.required, this.someValidator(this.ansat)); 

this.myForm = this.formBuilder.group({ 
     ansat: this.ansat, 
     helbred: this.helbred 
    }); 
+0

感謝您的建議!但我有個問題。使用這個我想使字段「helbred」必需如果ansat爲0,而不是返回null(有效)。我將如何做到這一點? – Vanquiza

+0

在我發送的調度程序中,someValidator函數可以檢查控件的值。看一個簡單的例子更新 – Riv

+0

嗯,我會嘗試重新翻譯。在我的情況下,我必須能夠使用條件驗證。在「required」的情況下,我想以某種方式返回「Validators.required」。這可能嗎? – Vanquiza