1

I have an input in my html as follows:

<ng-container *ngIf="({required: <some_condition>, invalid: <some_condition>}) as emailErrors">
    <input type="email" class="form-control" placeholder="Email" validate-onblur [class.is-invalid]="emailErrors.required || emailErrors.invalid" [attr.aria-invalid]="emailErrors.required || emailErrors.invalid" [attr.aria-describedby]="emailErrors.required || emailErrors.invalid ? 'email-error' : undefined">
    <div *ngIf="emailErrors.required" id="email-error">
        <p class="error-msg">{{messages.EMAIL_REQ}}</p>
    </div>
</ng-container>

Here in my <input> tag I'm repeting this condition 3 times: emailErrors.required || emailErrors.invalid.

Can I store this condition here in a variable, so that I do not have to repeat it?

P.S. I'm new in Angular

1
  • As answerd by @Yong Shaun You can use getter approach. Even angular material heavily using getter approach. You can check material code here:material.angular.io/guide/… Commented Jul 28, 2021 at 6:33

2 Answers 2

1

I would recommend you to use the template form of Angular. These are fairly simpler to implement.

In the code below make sure you give name property on the input field otherwise an error will be thrown, while working on with [(ngModel)]

<form #f="ngForm">
  <input type="email" class="form-control" placeholder="Email" name="mail" required [(ngModel)]="model.email" #mail="ngModel">
  <span *ngIf="mail.invalid">
        {{messages.EMAIL_REQ}}
  </span>
</form>

Sign up to request clarification or add additional context in comments.

2 Comments

How will this approach add aria-invalid and aria-describedby in the input tag?
@KeshavBhatiya Try the same approach [attr.aria-invalid]="mail.invalid".
1

Why not introduce an additional property in the wrapping <ng-container>? And seeing that emailErrors.invalid isn't used anywhere else, it could be removed if it's unneeded.

<ng-container *ngIf="({required: <condition_1>, reqOrInv: <condition_1> || <condition_2>}) as emailErrors">
  <input 
    type="email" 
    class="form-control" 
    placeholder="Email" 
    validate-onblur 
    [class.is-invalid]="emailErrors.reqOrInv" 
    [attr.aria-invalid]="emailErrors.reqOrInv" 
    [attr.aria-describedby]="emailErrors.reqOrInv ? 'email-error' : undefined"
  >
  <div *ngIf="emailErrors.required" id="email-error">
    <p class="error-msg">{{messages.EMAIL_REQ}}</p>
  </div>
</ng-container>

But as @YashwardhanPauranik noted in their answer, you're better off using Angular template driven or reactive forms. They provide more granular control.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.