Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Angular reactive form validation for dynamic field during submit

I am using the reactive form with dynamic field (productname). I can throw validation error if the form is submitted without filling the product name.

But when I clicked the Add button, the error "Enter Product Name" is appearing for every new inputs (formControlName="productname").
Also I given the stackblitz link
Please someone provide solution
enter image description here
https://stackblitz.com/github/reegan2024/mygithubrepo?file=src%2Fapp%2Fapp.component.html

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

When you submit, to show all the errors, use the method markAllAsTouched.

onSubmit(formvalue: boolean) {
  this.productFormarray.markAllAsTouched();
  if (formvalue == true) {
    this.openDialog();
  }
}

Since you want the error message to show only when the input is touched, you can fine tune the *ngIf to show only when it is touched this get’s rid of the complexity of checking form submitted and reduces the amount of HTML code, for more readability.

    <div
      *ngIf="productdetailsarray.at(i).get('productname')?.touched"
      style="font-size: 10pt; margin-top: 2pt; color:red;"
    >
      ...
    </div>

Stackblitz Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading