Keshav Bhatiya
Keshav Bhatiya

Reputation: 375

How to use one condition at multiple places in Angular?

I have the following form in my angular project:

<input type="email" class="form-control" placeholder="Email" validate-onblur aria-label="email">
<div *ngIf="!loginForm.controls['username'].pristine && loginForm.controls['username'].dirty && loginForm.controls['username'].hasError('required')">
    <p class="error-msg">{{messages.EMAIL_REQ}}</p>
</div>

The condition in the <div> tag in ngIf, I want to use this same condition in the <input> tag above, to add a class to that element, how can I achieve this? Something like this (myCondition):

<input ngClass="{'error': myCondition}" type="email" class="form-control" placeholder="Email" validate-onblur aria-label="email">
<div *ngIf="myCondition">
    <p class="error-msg">{{messages.EMAIL_REQ}}</p>
</div>

I am new to angular so don't know if it possible or not.

I thought of creating a function in the component and calling this function with onblur attribute, but with this approach I have to create several functions, because the form has several fields with their specific conditions.

So how can I do this in the html file itself?

Upvotes: 0

Views: 50

Answers (1)

Barremian
Barremian

Reputation: 31125

Yes it's possible, you could wrap the elements in a <ng-container> tag and extract the condition using *ngIf directive. It's commented out in the final rendered DOM.

<ng-container *ngIf="({res: (!loginForm.controls['username'].pristine && loginForm.controls['username'].dirty && loginForm.controls['username'].hasError('required'))}) as cond">
  <input type="email" [class.error]="cond.res" class="form-control" placeholder="Email" validate-onblur aria-label="email">
  <div *ngIf="cond.res">
    <p class="error-msg">{{messages.EMAIL_REQ}}</p>
  </div>
</ng-container>

I've also replaced [ngClass] with [class.error].


Although it's tempting to ignore the object in the *ngIf like

<ng-container *ngIf="(!loginForm.controls['username'].pristine && loginForm.controls['username'].dirty && loginForm.controls['username'].hasError('required')) as cond">
  ...
</ng-container>

it would counter-intuitive as the <input> would not be rendered when the condition is false. Wrapping it in an object would ensure the elements inside would be rendered even if the outer *ngIf in the <ng-container> would be false.

Upvotes: 1

Related Questions