angulartypescriptangular-ngmodelngmodelng-switch

Can't bind ngModel.errors in condition ngSwitchCase


Can't bind ngModel.errors in condition of *ngSwitchCase. But if i do this on *ngIf, it's work fine for me.
I wan't make a structure of displaying different's error's in condition of *ngSwitchCase.
StackBlitz sandbox

I tried different variations of *ngSwitchCase="name.errors?.required", but the only solution that works for me is *ngIf="name2.errors?.required". But I want to make 4 or more error conditions, and I think it would be more correct and readable to do it in *ngSwitchCase conditions, but after starting to learn Angular, I can't understand why this directive doesn't work. Thanks in advance for your answers


Solution

  • You can use ngSwitch with the condition value as true to create multiple if else statements like below!

    If the case is true, it will get displayed!

    Since minLength has an object like { "minlength": { "requiredLength": 5, "actualLength": 4 } } when the error is present we can use !!name.errors?.minlength to convert the value to a boolean and display the error!

    <div [ngSwitch]="true">
      <div class="error" *ngSwitchCase="name.errors?.required">The name is required</div>
      <div class="error" *ngSwitchCase="!!name.errors?.minlength">Minimum length of a name is 5!</div>
    </div>
    

    stackblitz demo