Skywalker
Skywalker

Reputation: 5194

Changing Input Element CSS based on Angular Reactive Forms validation

I have a simple reactive form like this:

this.loginForm = this._fb.group({
  email: ['', [Validators.required, Validators.pattern('^[A-Za-z0-9._%+-][email protected]$')]],
  password: ['', Validators.required]
});

The on HTML:

<!------------------------- PASSWORD FIELD ------------------------->
<div class="uk-margin">
  <input type="password" class="uk-input"
         placeholder="Enter Password" formControlName="password">

  <!----- VALIDATION WARNINGS ----->
  <div *ngIf="loginForm.get('password').touched">
    <div *ngIf="loginForm.get('password').hasError('required')">
      <div class="uk-text-danger"> Password is required.</div>
    </div>
  </div>
</div>

Then in CSS:

.ng-valid[required] {
   border: 5px solid #42A948;
 }

.ng-invalid[required] {
   border: 5px solid red; 
 }

The ng-valid/invalid CSS is being applied. I want to change the colour of the input fields border. But the CSS does not work form me. What am I doing wrong?

Update:

enter image description here

Upvotes: 1

Views: 4269

Answers (2)

Iancovici
Iancovici

Reputation: 5731

ng-invalid and ng-valid are always applied, you can customize css further to resolve this.

ng-valid.ng-touched {
  border: 5px solid #42A948;
}

ng-invalid.ng-touched {
  border: 5px solid red;
}

Upvotes: 1

Muhammad Ahsan Ayaz
Muhammad Ahsan Ayaz

Reputation: 1947

You could use [ngClass] for the conditional class based on the error. For example:

<!------------------------- PASSWORD FIELD ------------------------->
    <div class="uk-margin">
      <input
        type="password"
        class="uk-input"
        placeholder="Enter Password"
        formControlName="password"
        [ngClass]="{'has-error': loginForm.get('password').touched && loginForm.get('password').hasError('required')}">

      <!----- VALIDATION WARNINGS ----->
      <div *ngIf="loginForm.get('password').touched">
        <div *ngIf="loginForm.get('password').hasError('required')">
          <div class="uk-text-danger"> Password is required.</div>
        </div>
      </div>
    </div>

Then in CSS:

uk-input.has-error{
  /* your styles */
}

Upvotes: 0

Related Questions