Angular 2 array shape check

How are you going to access element validators in FormArray?

For instance:

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

How would you decide to set the condition on modelif the year was <1990?

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

+4
source share
1 answer

Here is a simple example of validating an array of forms. Below is 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

A group of forms inside an array of forms can take the second parameter of the object with the key validator , where you can place your own validator. Below is 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

, , ( , ). 1990 "", . null, ( , ) true ( ). , !

+2

Source: https://habr.com/ru/post/1653054/


All Articles