Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why class is not applying on input element if it's invalid in Template driven form Angular 4?

I used a template driven form for my login page. I want a red border on input elements if they are invalid or have any errors but the class borderRed is not being added on an input element when the input is blank or invalid.

<form (ngSubmit)="f.form.valid && signin()" #f="ngForm" class="m-login__form m-form" action="">
  <ng-template #alertSignin></ng-template>

  <div class="form-group form-md-line-input form-md-floating-label">
    <label>
      Email <span class="text-danger">*</span>
    </label>
    <input [class.borderRed]="email.invalid" class="form-control m-input" type="text" required="required" name="email" [(ngModel)]="model.email" #email="ngModel" autocomplete="off">
  </div>

  <div class="form-group form-md-line-input form-md-floating-label">
    <label [pTooltip]="attachementTooltipmsg" tooltipPosition="top" for="form_control_1">
      Password <span class="text-danger">*</span>
    </label>
    <input [class.borderRed]="password.invalid" class="form-control m-input" required="" name="password" type="password" [(ngModel)]="model.password" #password="ngModel">
  </div>

  <div class="m-login__form-action">
    <button [disabled]="loading" [ngClass]="{'m-loader m-loader--right m-loader--light': loading}" id="m_login_signin_submit" class="btn btn-focus m-btn m-btn--pill m-btn--custom m-btn--air">
      Sign In
    </button>
  </div>
</form>
like image 974
Parth Savadiya Avatar asked Apr 27 '18 12:04

Parth Savadiya


People also ask

How do I validate in template driven form?

To add validation to a template-driven form, you add the same validation attributes as you would with native HTML form validation. Angular uses directives to match these attributes with validator functions in the framework.

What is the use of [( ngModel )] in template driven form?

The ngModel directive declared in the FormsModule lets you bind controls in your template-driven form to properties in your data model.


1 Answers

Use this

   <input [class.borderRed]="email.touched && !email.valid" class="form-control m-input" type="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$" required name="email" [(ngModel)]="model.email" #email="ngModel" autocomplete="off">

Check out StackBiltz

Edited code

like image 191
Miran Parkar Avatar answered Nov 02 '22 03:11

Miran Parkar