0

this is my primary code:

get emailFormArray() {
  return this.formGroup.get("emails") as FormArray;
}

public ngOnInit() {
  this.formGroup = this.formBuilder.group({
    emails: this.formBuilder.array([]),
  });
  this.addEmailFormGroup();
}

public addEmailFormGroup() {
  this.emailFormArray.controls.push(
    this.formBuilder.group({
      email: ['', Validators.email],
    }),
  );
}

and in my template

{{ formGroup.valid }}
{{ emailFormArray.valid }}
<ng-container *ngFor="let email of emailFormArray.controls">
  {{ email.valid }}
  {{ email.get('email').valid }}
</ng-container>

When I input a invalid email, the result in template is true true false false, why the formGroup and emailFormArray is valid? Thank you!

2
  • 1
    Off Topic - You can omit public from public ngOnInit Commented Nov 9, 2019 at 12:54
  • 1
    Yes thank yout, but I prefer this code style Commented Nov 11, 2019 at 6:35

2 Answers 2

15

I found the reason. I should use this.emailFormArray.push instead of this.emailFormArray.controls.push

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

1 Comment

Even I was about to post to the same answer :)
0

I faced the same issue when load data from database and update data, it did not keep validation rule. The problem that I set direct value to form control as

loadSlideItemFromDB(slideShowItem): FormArray {
    const formArray = new FormArray([]);
    slideShowItem.forEach(item => {
      formArray.push(this.fb.group({
        id: item.Id,
        slideShowId: item.SlideShowId,
        pageType: item.PageType,
        linkUrl: item.LinkUrl,
        pageTitle: item.PageTitle
      }))
    });

    return formArray;
  }

After refactoring code, I create form array with validation rule first and then patchValue for it.

I share this for whom concerned.

loadSlideItemFromDB(slideShowItem): FormArray {
    const formArray = new FormArray([]);
    slideShowItem.forEach(item => {
      let group = this.fb.group({
        id: [''],
        slideShowId: [''],      
        pageType: ['1', Validators.required],
        linkUrl: ['', Validators.required],
        pageTitle: ['']
      })
      group.patchValue({
        id: item.Id,
        slideShowId: item.SlideShowId,
        pageType: item.PageType,
        linkUrl: item.LinkUrl,
        pageTitle: item.PageTitle
      });
      formArray.push(group);
    });

    return formArray;
  }

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.