ngClass causing styling issue when applying styles

When I use class names like error and info, the CSS works fine.

For example, in this Angular app (latest version) here: https://stackblitz.com/edit/github-i4uqtt-zrz3jb.

However, when I try to rename the CSS classes and add more styles, like in the example below, the CSS and [ngClass] no longer seem to work properly. Any suggestions or ideas?

#HTML

<div fxLayout="row" fxLayoutAlign="space-between">
  <div fxLayout="column" fxFlex="0 0 7%">
    <mat-icon 
    [ngClass]="password.hasError('mininum') ? 'error-check-outline' : 'info-check-outline'">
    check_circle_outline </mat-icon>
  </div>
  <div fxLayout="column" fxFlex="0 0 100%">
    <span 
    [ngClass]="password.hasError('mininum') ? 'text-info-error' : 'text-info'">
    8 characters mininum</span>
  </div>
</div>

#ts

validateMinimumPassword: ValidatorFn = (control: AbstractControl) => {
  if (control.value.length < 8) {
    return { minimum: true };
  }
  return null;
};

#CSS

.text-info {
  font-family: Inter;
  font-style: normal;
  font-weight: normal;
  font-size: 14px;
  color: #4caf50;
  font-family: Manrope;
  margin-top: 2.5px;
}

.text-info-error {
  font-family: Inter;
  font-style: normal;
  font-weight: normal;
  font-size: 14px;
  color: #DDD;
  font-family: Manrope;
  margin-top: 2.5px;
}

.error-check-outline {
  transform: scale(.74);
  color: #DDD;
}

.info-check-outline {
  transform: scale(.74);
  color: #4caf50;
}

Answer №1

To properly utilize the ngClass directive, make sure to encapsulate your conditions within curly braces and adjust the syntax accordingly.

Here's an example:

[ngClass]="{'error-check-outline': password.hasError('minimum'), 'info-check-outline' : !password.hasError('minimum'
)}"

Answer №2

To ensure everything runs smoothly, make sure to correct the typo from mininum to minimum.

Here's a working example: https://example.com


Update: Why it appears green

In your code, you used the expression

"password.hasError('mininum') ? 'text-info-error' : 'text-info'"

The ternary(conditional) operator syntax follows this pattern,

condition ? exprIfTrue : exprIfFalse

In this case, password.hasError('mininum') contains a typo and returns null, which is considered as falsey. As a result, the left side of the expression becomes false, causing the selection of .text-info. Since this style is associated with the color green, it displays as green.

Answer №3

One approach is to create a function that determines the class based on a condition

assignClass(type) {
  if (type == 'minimum') {
    return 'class-one';
  } else if (type == 'maxmimum') {
    return 'class-two';
  }
}

Then, you can use this function in your HTML like this

<div [ngClass]="assignClass('minimum')"><div>

By following this method, you can keep your HTML code organized and easier to read

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

Error encountered when referencing prop on textarea: 'There is no suitable overload for this call'

I've been referring to the documentation in order to set a reference using the useRef hook, with the goal of being able to programmatically clear an input field. However, when I add ref as a prop to a textarea, it triggers a lint error saying that no ...

Issues with `Float:left` not functioning as expected on a div with dynamically changing

I'm currently working on setting up a base div that I can easily duplicate whenever I need to add new content to my website. Here's how the initial HTML structure looks: <div class="post"> <p class="date">17/03/1014</p> <h1& ...

Ways to apply CSS styles dynamically within a v-for loop

Despite searching through the VUE official website and various other sources, I have not been able to find a satisfactory solution. I am reaching out for assistance, thank you in advance. <div class="tag-item" :ref="`tagItem_ ...

Checking conditions sequentially in Angular

I have a unique use case that requires me to verify certain conditions. If one condition fails, I should not proceed to the next one. Instead, based on the failed condition, I need to display a dialog with a title and description explaining what went wrong ...

Dynamic class name changes in Angular.js based on JSON object

I am trying to dynamically change the class of an <li> element based on the category value I am getting, but for some reason the class name won't update. Here is the code snippet: <div id="content"> <ul id="container" ng-controller ...

Can anyone suggest a way to change the orientation of mapped items from column to row?

In my React app, I am creating a keyboard using the following component: Keypad.js const Keypad = () => { const letters = [ 'Q', 'W', 'E', 'R', 'T', ...

Troubleshooting: Issue with Chrome's CSV Export Functionality in JavaScript/AngularJS

Currently, I am troubleshooting an issue with exporting a CSV file from a data table on a web application. The export functionality works fine on all browsers except for Chrome when the export button is clicked. I have been trying to solve this problem for ...

Tips for indicating an error when an array contains empty values

Object = { 0 : { NAME: 'A' , PET :'DOG' , AGE : 'NINE' }, 1 : { NAME: 'B' , PET :'CAT' , AGE : 'TEN' }, 2 : { NAME: 'C' , PET :'TURTLE' , AGE : '' } } HT ...

Utilizing AngularJS routes to load a specific URL when accessing a page for the first time

Working on developing a Single Page Application using AngularJS, my configuration settings appear as follows: app.config(["$routeProvider", function($routeProvider) { return $routeProvider .when("/", { redirectTo: " ...

How to prevent click events and still enable scrolling within a DIV using CSS/JS

Basically, I am looking to enable scrolling within a DIV while also disabling click events. Any suggestions on how this can be achieved? Appreciate any help! ...

Guide to Designing a Three-Column Layout Using Only CSS

I'm currently facing an issue with the alignment of the content section on my webpage which consists of three columns. The DIVs are not floating as expected. Below is the code I am using: <div id="content"> <asp:ContentPlaceHolder ID="Ma ...

The background-size property fails to function properly on mobile devices

It's really puzzling why this issue is happening, perhaps it's due to my fatigue. The problem lies in the fact that the "background-size" property isn't functioning on my mobile devices; however, it works perfectly when I try to simulate it ...

What are some creative ways to design drop-down menus within an email?

The snippet of code I am currently using lacks the ability to format text, and it does not allow content below dropdown items to shift down properly in an email. <select> <option value="first">First-time users of the Vanguard Events app:&l ...

What is the best way to run tests on this method using Jest?

import { format, getDaysInMonth, getMonth, getYear, isValid, parse } from "date-fns"; export class DateService { public getDaysInMonth(month?: Date) { return getDaysInMonth(month || new Date()); } What is the best way to test this func ...

Creating an Angular form group that includes dynamic form controls with custom form control names

Seeking to implement a formGroup that dynamically adjusts based on JSON data like this: const LIMITS: Limit[] = [ { id: 'limit1', value: 1000, disabled: false }, { id: 'limit2', value: 500, disabled: tru ...

Synchronizing Ionic Data Between Screen and Controller

I am new to the Ionic framework and encountering a data synchronization issue. The problem occurs when the interface calls a function on the controller, which removes an item from an array called lupulos. This array is linked with Angular's ng-repeat= ...

Is it advisable to use Angular $resource JSON Callback if it's not functioning correctly?

I am in the process of creating a resource to send data to my controller for an existing API that I need to connect with. Unfortunately, I do not have the ability to make any changes on the backend. Current state of my Resource factory: 'use strict& ...

Resetting the width of a CSS-styled div to its default maximum width

I have a set of automatically generated div containers that contain label and data information. For example: <div class="display-label"> @Html.DisplayNameFor(model => model.BusinessPhone) </div> <div class="display-field"> @H ...

Obtaining images from JSON data and displaying them in a modal using AngularJS

Utilizing AngularJS to retrieve a JSON file: { "albumId": 1, "id": 1, "title": "accusamus beatae ad facilis cum similique qui sunt", "url": "http://placehold.it/600/92c952", "thumbnailUrl": "http://placehold.it/150/92c952" }, and showcasing it with ...

Unchanging bottom section with changeable information

I have a unique website design in mind that involves using an image as the background and placing the content within a box. View my website design here However, I am facing an issue with a specific page on this website. The page contains accordion buttons ...