2

I have created form with FormArray like below mentioned

    this.createModuleForm = this.fb.group({
        artefactType: ['', Validators.required],
        uploadDocuments: this.fb.array([]),
    });

then I'm pushing the object into the FormArray

        formArray.push(this.fb.group({name: event.name, url: event.url, submittedBy: 'siva', role: this.currentUser.value.role}));

Problem: If the uploadDocuments(FormArray) is empty, need to make Form is invalid and UploadDocuments should be mandatoary

2
  • You can do via check length uploadDocuments formArray in template Commented Feb 19, 2019 at 7:12
  • use FormArray.setErrors() to set your errors Commented Feb 19, 2019 at 7:27

1 Answer 1

4

create custom Validator

I have created minAdded function that will check wheather the current formarray has minimum one group or not

component.ts

 this.createModuleForm = this.fb.group({
        artefactType: 'De',
        uploadDocuments: this.fb.array([], minAdded(1))
 })

    function minAdded(min = 1) {
      const validator: ValidatorFn = (formArray: FormArray) => {
        const minAdded = formArray.controls
          .map(control => control.value).length;    
        return minAdded >= min ? null : { required: true };
      };    
   return validator;
 }

Ref: https://coryrylan.com/blog/creating-a-dynamic-checkbox-list-in-angular Example:https://stackblitz.com/edit/angular-dcy9z9

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.