2016-08-30 60 views
4

如何訪問FormArray中某個項目的驗證器?Angular 2 Form Array Validation

例如:

{ 
    firstName: 'Joe', 
    lastName: 'Dirt', 
    cars: [ 
     { make: 'A', model: 'B', year: 1990 }, 
     { make: 'C', model: 'D', year: 1990 } 
    ] 
} 

你怎麼會去上model設定一個條件,如果一年是1990年<?

我完全理解如何使用API​​來獲取不在FormArray內的屬性。

回答

2

下面是如何驗證表單數組的簡單示例。下面是app.component.ts

import { Component, OnInit } from '@angular/core'; 
import { FormBuilder, FormGroup, FormControl, FormArray } from '@angular/forms'; 
import { CustomValidator } from './custom-validators'; 
@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: [`./app.component.css`] 
}) 
export class AppComponent implements OnInit { 
    person: FormGroup; 
    carsArray: FormArray; 
    constructor(private fb: FormBuilder) { } 
    ngOnInit() { 
    this.person = this.fb.group({ 
     firstName: this.fb.control('Joe'), 
     lastName: this.fb.control('Dirt'), 
     cars: this.fb.array([ 
     this.fb.group({ 
      make: this.fb.control('a'), 
      model: this.fb.control('b'), 
      year: this.fb.control(1990) 
     }, { 
      validator: CustomValidator.checkYearModel() 
      }) 
     ]) 
    }); 
    this.carsArray = this.person.get('cars') as FormArray; 
    } // End Of Init 
} // End of Class 

表單集團的表單數組內可以採取的第二個目的參數與驗證的關鍵,你可以把你的自定義驗證。下面是定製validator.ts

export class CustomValidator { 
    static checkYearModel() { 
     return (control) => { 
      const year = control.value.year; 
      const model = control.value.model; 
      let valid: boolean; 
      (year < 1990 && model !== 'mustang') ? valid = false : valid = true; 
      return (valid) ? null : { checkYearModel: true }; 
     }; // End of return (control)=> 
    } // End of method 
} // End of Class 

在這種情況下,我創建的變量等於一年和控制(這是成組你下把驗證)的模型值。如果年份在1990年以下,那麼該模型必須是「野馬」纔是有效的。如果有效變量爲真(這意味着控制將是有效的),則此方法返回null,否則將返回值爲true的對象鍵(這將使控制無效)。希望這有助於!