Skip to content

Show errors from different controls conditionally #28

@dev054

Description

@dev054

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ ] Performance issue
[ ] Feature request
[ ] Documentation issue or request
[x] Support request
[ ] Other... Please describe:

Problem

I have this component:

function invalidTouched(control: AbstractControl | null | undefined): boolean {
  return !!(control?.invalid && control.touched);
}

export class CustomErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null): boolean {
    return invalidTouched(control) || invalidTouched(control?.parent);
  }
}

@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  selector: 'app-test',
  template: `
    <form errorTailor [formGroup]="formGroup">
      <!-- password field omitted for brevity --> 
      <mat-form-field>
        <mat-label>Password confirmation</mat-label>
        <input
          matInput
          required
          formControlName="passwordConfirmation"
          type="password"
          [controlErrorAnchor]="passwordConfirmationControlErrorAnchor"
          [errorStateMatcher]="customErrorStateMatcher"
        />
        <mat-error>
          <ng-template
            controlErrorAnchor
            #passwordConfirmationControlErrorAnchor="controlErrorAnchor"
          ></ng-template>
          <!-- Here I want to show passwordConfirmation OR formGroup errors, if passwordConfirmation has no errors. -->
        </mat-error>
      </mat-form-field>
    </form>
  `,
})
class TestComponent {
  readonly customErrorStateMatcher = new CustomErrorStateMatcher();
  readonly formGroup = this.formBuilder.group(
    {
      password: ['', [Validators.required]],
      passwordConfirmation: ['', [Validators.required]],
    },
    { validators: this.equalToValidator },
  );

  equalToValidator(group: FormGroup) {
    const password = group.get('password').value;
    const passwordConfirmation = group.get('passwordConfirmation').value;

    return password === passwordConfirmation ? null : { equalTo: true }     
  }
}

... and the problem is that I need to show the equalTo error on the passwordConfirmationControlErrorAnchor template, but only if passwordConfirmation control itself has no error.

Is that possible?

Environment


Angular version: 11.0.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions