Dynamically apply classes in Angular using ngClass

Help needed with setting a class dynamically. Any guidance is appreciated.

Below is the class in my SCSS file:

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

In my ts file, there's a variable named isEmailValid. When this variable is set to false, I want the border to appear; otherwise not. Here's my code:

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 implementing the above code, the class is not being applied. What could be the issue? Please provide some advice.

Answer №1

It slipped your mind to include a . in the form-validation class in the CSS. Everything else appears to be in order.

CSS

Modify

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

to

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

TypeScript

// Perform a service call to determine if the email is valid or not

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

View a working example here - https://stackblitz.com/edit/angular-ejvaau

Answer №2

When configuring both scenarios, the error lies in assigning a value of true.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting: Angular universal 7 unable to initiate HTTP requests

Recently, I've embarked on the journey of converting my Angular 7.2.0 application into an Angular universal app. The process has been successful in rendering server-side and transferring state swiftly on high-performance PCs and fast internet connecti ...

Tips for styling your Angular Material Card on mobile devices

Currently, I am very happy with my desktop layout which looks like this: https://i.stack.imgur.com/tG0pw.png However, when it comes to the mobile version of my site, here is what I have so far: https://i.stack.imgur.com/KD1hh.jpg While I do like the ho ...

Angular: Variable `app` has not been defined

I am working on a simple MEAN stack app and it is almost up and running, but I encountered an uncaught reference error when it tries to redirect to the index page. The server seems to be running fine and the browser displays "Loading..." as expected on the ...

Failure to log in to Facebook via Angular and Google Firebase due to URL being blocked

I am currently in the process of developing a web application that aims to gauge political popularity. To ensure accurate polling data, users will need to authenticate their social media accounts including Facebook, Twitter, and Google. For the front-end ...

Issue regarding retrieving the image using TypeScript from an external API

Hey developers! I'm facing an issue with importing images from an external API. I used the tag: <img src = {photos [0] .src} /> but it doesn't seem to recognize the .src property. Can anyone shed some light on how this is supposed to work? ...

Encountering a problem when parsing a JSON file in Angular 2

When attempting to access the config.json file in my Angular2 service, I have encountered an issue. load() { return new Promise((resolve, reject) => { this.http.get('./config.json') .map(res => res.json()) ...

There are a pair of Ionic2 menus; one is currently visible while the other remains hidden

I am having an issue with my Ionic2 app where I have two pages, each with similar menus named XXX.html. One page displays its menu correctly, but the other does not show its menu at all. Is there a limitation in Ionic2 that prevents having two menus on the ...

Transitioning from LESS to SASS involves adapting responsive breakpoints

Adapting from Less to Sass has been my current focus. I have defined responsive breakpoints in Less variables: /* Breakpoints */ @break1:~"(max-width: 570px)"; @break2:~"(min-width: 571px) and (max-width: 1002px)"; @break3:~"(min-width: 1003px)"; These ...

Creating a Mocha+Chai test that anticipates an exception being thrown by setTimeout

Here is what I have: it('invalid use', () => { Matcher(1).case(1, () => {}); }); I am trying to ensure that the case method throws an exception after a delay. How can I specify this for Mocha/Chai so that the test passes only if an exce ...

The installation process was unsuccessful due to an error in the postinstall script for [email protected]

While attempting to run npm install, an error message is displayed: Failed at the <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e38d8c8786ce90829090a3d7cdd6cdd3">[email protected]</a> postinstall script. I hav ...

react-hook-form replaces the onChange function causing delays in updating the value

Recently, I created a unique Select component utilizing useState and onChange. I attempted to integrate this custom component with the powerful react-hook-form. Allow me to share the code snippet for the bespoke Select component. const Select = forwardRef ...

What sets apart a class from a service in NativeScript?

I am embarking on the journey of learning Nativescript + Angular2, and while reading through the tutorial, I came across this interesting snippet: We’ll build this functionality as an Angular service, which is Angular’s mechanism for reusable classes ...

What is the reason for the lack of overlap between types in an enum?

I'm having trouble understanding why TypeScript is indicating that my condition will always be false. This is because there is no type overlap between Action.UP | Action.DOWN and Action.LEFT in this specific scenario. You can view the code snippet and ...

Implementing a conditional chaining function in TypeScript

I'm currently facing an issue while implementing a set of chained functions. interface IAdvancedCalculator { add(value: number): this; subtract(value: number): this; divideBy(value: number): this; multiplyBy(value: number): this; calculate( ...

Develop a component library for Angular 2 without incorporating inline styles

I recently came across an interesting article about developing an Angular 2 component library that utilizes inline styles. Is there a method to create a library in Angular 2 without relying on inline styles? I also stumbled upon another resource, but it d ...

What is the reason behind requiring {[param: string]: string | string[]} for the HTTP GET attribute [params]?

Problem Statement An error occurs during type inference in this.http.get() Error TS2322: Type 'Observable<ArrayBuffer>' is not assignable to type 'Observable<IInfo[]>'. Type 'ArrayBuffer' is missing the followin ...

What is the proper way to conduct unit testing on a function that is invoked in a service's constructor

Is there a way to verify, within the service's spec file, that a function is invoked in the constructor? Consider the following example: @Injectable({ providedIn: 'root' }) export class myService { constructor() { this.myF ...

The TypeScript compiler throws an error when encountering nulls in conjunction with the isNull function

Whenever I set strictNullChecks: true in tsconfig.json and utilize the isNull function for null checks, the compiler throws the error TS2531: Object is possibly 'null'. Interestingly, isNull doesn't trigger any errors in VsCode, however, the ...

Unit Testing with Angular: Testing the setValueControl function

I am currently in the process of writing unit tests for a straightforward function that assigns controls to various values. fillFormAssociazioneVeicolo() { if (this.aaa) { setValueControl( this.aaa.targaTelaio, this.form.get(&apos ...

What is the method to insert a new <input> element after the last input field has been filled in

I recently started working on a form using StackBlitz, but I've hit a roadblock and need some guidance on how to proceed. My goal is to achieve a similar effect like the one shown in this gif: https://i.stack.imgur.com/76nsY.gif and I'd like to ...