Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get validation error list of form control in angular 6

I'm using angular 6 with reactive forms. I want to show validation messages dynamically. And I wrote some code like below. But I take this error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays. How can I take list of errors of input?

.html file

<form [formGroup]="myForm" (ngSubmit)="save()">
    <input type="text" formControlName="studentName">

    <div *ngFor="let err of myForm.controls.studentName.errors">
      <div>You entered not valid input</div>
    </div>
</form>

.ts file

this.myForm = this.formBuilder.group({
  studentName: ['', Validators.required, Validators.minLength(3)]
});
like image 916
realist Avatar asked Mar 04 '23 20:03

realist


1 Answers

I found the solution. My mistake is, I thought that myForm.controls.studentName.errors is an array. But, it is not array, it's an object. So, below code working perfectly.

.html file

<form [formGroup]="myForm" (ngSubmit)="save()">
    <input type="text" formControlName="studentName">

    <div *ngFor="let err of getErrorList(myForm.controls.studentName.errors)">
      <div>You entered not valid input</div>
    </div>
</form>

.ts file

this.myForm = this.formBuilder.group({
  studentName: ['', Validators.required, Validators.minLength(3)]
});

getErrorList(errorObject) {
  return Object.keys(errorObject);
}
like image 161
realist Avatar answered Mar 12 '23 17:03

realist