Search code examples
angulartypescriptangularjs-scopeangular-directive

How to prevent multiple error message getting displayed in the angular html?


Hi the following is a snippet of code in my angular html file. I am trying to implement an if elseif(condition) elseif(condition) using ngif and ng-container.

What I want to achieve is only one code block should print the error. In other words I don't want to print two error messages. I don't know why my code is not working.

For example, currently if formGroup.hasError('invalidPasswordStrength') and formGroup.hasError('blacklistedPassword') are true it prints two error messages.

What I expect is if both of them are true I want to print the error message pertaining to formGroup.hasError('invalidPasswordStrength') .

I have tried options like this for example:

*ngIf="formGroup.hasError('passwordConfirmation') && !(formGroup.hasError('invalidPasswordStrength') || formGroup.hasError('blacklistedPassword')).

It works but it is not clean

<ng-container *ngIf="formGroup.hasError('passwordConfirmation'); else second">
          <alert type="danger" dismissable="false">
            {{ 'VALIDATION.ERRORS.MATCHING_PASSWORDS' | translate }}
          </alert>
        </ng-container>

        <ng-container #second *ngIf="formGroup.hasError('invalidPasswordStrength'); else third">
          <alert type="danger" dismissable="false">
            {{ 'VALIDATION.ERRORS.PASSWORD_STRENGTH_INVALID' | translate }}
          </alert>
        </ng-container>

        <ng-container #third *ngIf="formGroup.hasError('blacklistedPassword'); else fourth">
          <alert type="danger" dismissable="false">
            {{ 'VALIDATION.ERRORS.PASSWORD_NOT_PERMITTED' | translate }}
          </alert>
        </ng-container>

        <ng-container #fourth *ngIf="formGroup.hasError('passwordMatchingUserDetails')">
          <alert type="danger" dismissable="false" >
            {{ 'VALIDATION.ERRORS.PASSWORD_MATCHING_USER_DETAILS' | translate }}
          </alert>
        </ng-container> 

Solution

  • Why not handle this logic in the validator. I would just do one validator and handle all the errors there, there you can also add them in the order you want. So pseudocode:

    constructor(private fb: FormBuilder) {
      this.myForm = this.fb.group({
        name: ['']
      }, { validator: this.myValidator});
    }
    
    myValidator(form: FormGroup) {
      // begin every time by removing all errors
      if (form) {
        form.setErrors(null);
        if ('some conditions here') {
          return { 'err1': true }
        }
        if ('some conditions here') {
          return { 'err2': true }
        }
        if ('some conditions here') {
          return { 'err3': true }
        }
        return null;
      }
      return null;
    }
    

    This validator then just returns one error at a time (if error exists).