简体   繁体   中英

Angular2 FormGroup in FormArray validation

I have the following model:

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

I need to validate a contents FormArray of this parent FormGroup :

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

For each Content in my contents FormArray , I validate the model with the following content FormGroup :

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

For now, I add the following content FormGroup to my contents FormArray to validate each Content :

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

But with this approach I can't validate these rules:

  • If one of the Content fields are filled up then content validation occurs (which means adding the content FormGroup to the contents FormArray )
  • If none of the content fields are filled up then no content validation occurs (which means removing the content FormGroup of the contents FormArray if present)
  • If lang of a Content is the defaultLang of the parent FormGroup , then the content is required.

Questions

Is there a work around of adding/removing the content FormGroup of the contents FormArray just with validators?

Is there a way to do it with Angular native validators only?

Do I need to create a custom validator? If yes, do you have great example to do so with FormArray ?

You can add validator to the group like below

 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;
        }
    };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM