#@else {} not working as expected?

1 messages · Page 1 of 1 (latest)

pale cave
#

In this example, I have a reusable mat-form-field that should display mat-error 'required' if it has the error, else it should display mat-hint 'Optional'. The mat-hint never get displayed. Is this expected?

<mat-form-field>
  <mat-label>Comments</mat-label>
  <textarea matInput [formControl]="commentControl"></textarea>
  @if (commentControl.hasError('required')) {
    <mat-error>Required</mat-error>
  } @else {
    <mat-hint>Optional</mat-hint>
  }
</mat-form-field>
rain path
#

I'm not sure exactly why it happens but:

  • without the @else, it works fine, and the error is displayed insted of the hint, so it actually has the effect you want
  • most importantly, that doesn't make much sense: a field isn't optional just because it doesn't have an error of type required. That just means that the user happens to have entered something in the required field.
pale cave
#

hasError('required') will be true even if not touched yet

#

mat-error will still be hidden

#

I use this component multiple time in my form and sometime it's required and other time it isin't.

#

I don't want Optional to display if it has the error, this is a bug or something that happens with mat-hint that i'm unaware of

rain path
#

OK, but have you read my second comment (starting with "most importantly")?

pale cave
#

ahh yes true, but even else if does not work

#

well wait im not sure i tried

#

OK, I don't think i can make it happen xD

#

Ok I want with:

protected commentControlHasValidatorRequired(): boolean {
  return this.commentControl.hasValidator(Validators.required);
}
#

But yeah can't fix the else problem 😛

pale cave
#

Well the solution was quite easy after all:

@if (commentControlHasValidatorRequired()) {
  <mat-error>Required</mat-error>
}

@if (!commentControlHasValidatorRequired()){
  <mat-hint>Optional</mat-hint>
}