Sam
Sam

Reputation: 15761

Angular 2 Form Array Validation

How do you go about accessing the validators of an item in a FormArray?

For example:

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

How would you go about setting a condition on model if year was < 1990?

I fully understand how to use the API to get to properties just not inside a FormArray.

Upvotes: 4

Views: 1903

Answers (1)

Stephen McDonald
Stephen McDonald

Reputation: 106

Here is a simple example of how to validate a Form Array. Below is the 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

The Form Group inside the Form Array can take a second object parameter with a key of validator where you can place your custom validator. Below is the custom-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

In this case I created variables equal to the year and the model values of the control(which is the Form Group you put the validation under). If the year is under 1990 the model must be a 'mustang' to be valid. This method returns null if the valid variable is true(which means control will be valid) or will return an object key with a value of true(which will make control invalid). Hoped this helps!

Upvotes: 3

Related Questions