Angular ngClass: apply class dynamically

596 Views Asked by At

I am unable to set the class dynamically. Please guide me through. Thanks.

I have a class in SCSS file as below:

.form-validation.invalid {
    border: 2px solid red
}

My ts file has a variable names isEmailValid, when ever this variable is false the border should appear else not. My code is as below:

HTML:

<input type="email" class="form-validation" [ngClass]="{'invalid': isEmailValid}"

TS:

//make service call and decide whether email is valid or not
if(value){            //value is the service response
    this.isEmailValid = true;
} else {
    this.isEmailValid = false;
}

After the above code the class is not getting applied. Where am I going wrong? please guide.

2

There are 2 best solutions below

2
On

You had forgotten to put . in form-validation in css. Rest are looking fine.

css

Change

form-validation.invalid {
    border: 2px solid red
}

to

.form-validation.invalid {
    border: 2px solid red
}

ts

//make service call and decide whether email is valid or not

if(value){            //value is the service response
    this.isEmailValid = true;
} else {
    this.isEmailValid = false;
}

Working sample is here - https://stackblitz.com/edit/angular-ejvaau

0
On

in both cases you are setting value true. which is a mistake.

if(value){            //value is the service response
    this.isEmailValid = true;
} else {
    this.isEmailValid = true;
}