Angular2 FormGroup in FormArray validation

I have the following model:

export interface Content {
  lang: string;
  title: string;
}

I need to check a of contents FormArraythis parent FormGroup:

this.formBuilder.group({
  defaultLang: ['', Validators.required],
  contents: this.formBuilder.array([], Validators.minLength(1))
});

For everyone Contentin mine contents FormArray, I test the model as follows content FormGroup:

this.formBuilder.group({
  lang: ['', Validators.required],
  title: ['', Validators.required]
});

I am currently adding the following content FormGroupto mine contents FormArrayto test each Content:

(<FormArray>parentFormGroup.controls['contents'])
    .push(this.contentFormGroup);

But with this approach, I can not confirm these rules:

  • If one of the fields is filled Content, then the content is checked (which means adding content FormGroupto contents FormArray)
  • If none of the content fields is completed, the content is not checked (which means deletion content FormGroup contents FormArray, if any)
  • If langfor Contentis defaultLang parent FormGroup, then content is required.

Questions

/ content FormGroup contents FormArray ?

Angular?

? , , FormArray?

+6
1

,

 this.group = this.formBuilder.group({
        lang: ['', Validators.required],
        title: ['', Validators.required]
    });

    this.group.setValidators([          
        this.titleRequiredValidator(),
    ]);



    private titleRequiredValidator(): ValidatorFn {
        return (group: FormGroup): { [key: string]: any } => {
        const langControl = group.controls.lang;
        const titleControl = group.controls.title;

        if (langControl.value !== '' && titleControl.value == '')) {
            const error = { required: true };
            titleControl.setErrors(error);
            return error;
        }            
        else {
            titleControl.setErrors(null);
            return null;
        }
    };
}
0

All Articles