angular materror check dropdown ngmodel object valid

88 views Asked by At

Good day,

Normally, I will set the drop down value into a string, for example:

<mat-form-field>
   <mat-select name="searchReloadType2" placeholder="reload to" required #searchReloadType2="ngModel"
      [(ngModel)]="reloadTypeObjStr" >
      <mat-option [value]="rReloadType.key" *ngFor="let rReloadType of reloadTypeList">{{ rReloadType.label }}
       </mat-option>
   </mat-select>
    <mat-error *ngIf="!searchReloadType2.valid">
        reloadTo is required
    </mat-error>
  </mat-form-field>

Where rReloadType.key is a string value from drop down that set to reloadTypeObjStr, and if user click on the drop down list, but didnt select any value, then will show "reloadTo is required" under the drop down there.

I wish to have a dropdown list which is set the value to an object instead of a string, for example:

     <mat-form-field>
       <mat-select name="searchReloadType" placeholder="reload to" required #searchReloadType="ngModel"
          [(ngModel)]="reloadTypeObj" >
          <mat-option [value]="rReloadType" *ngFor="let rReloadType of reloadTypeList">{{ rReloadType.label }}
           </mat-option>
       </mat-select>
        <mat-error *ngIf="!searchReloadType.valid">
            reloadTo is required
        </mat-error>
      </mat-form-field>

where rReloadType is an object (instead of string) from drop down, and set to reloadTypeObj, which is an object. At this point, if user didnt select any value from this drop down, the reloadTo is required wont show, the mat-error does not work at this point.

I would like to ask for advise, is there anything I can do for this? Or angular does not support this? I must use string value instead of object value for drop down?

1

There are 1 answers

1
Lord GabeN On

Hope you are doin good.

I tried to reproduce your problem, and it is working fine in both the cases, I don't see any problem here. https://stackblitz.com/edit/angular-mat-form-field-fbtask?file=app%2Fform-field-prefix-suffix-example.html

Also, I would suggest you to use searchReloadType.errors?.required inside mat-error, instead of !searchReloadType.valid. So, you can also use errors?.required, errors?.pattern to check the pattern, errors?.minlength and errors?.maxlength, etc. These would be more useful when you are dealing with variety of inputs.

Peace out.