Keshav Bhatiya
Keshav Bhatiya

Reputation: 375

How to prevent repetition in Angular html?

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

Upvotes: 0

Views: 463

Answers (2)

Barremian
Barremian

Reputation: 31125

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.

Upvotes: 0

Yashwardhan Pauranik
Yashwardhan Pauranik

Reputation: 5556

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>

Upvotes: 1

Related Questions