Angular Tips: Mastering the Art of Setting Multiple Conditions using ngClass

Currently, I am in the process of developing my own UI library by utilizing angular and Tailwind. However, I have encountered a challenge while using ngClass :

  <button
    [ngClass]="{
      'px-4 py-2 text-sm': size === 'md',
      'px-4 py-2 text-base': size === 'lg',
    }"
  >
    My Button
  </button>

My objective is to apply one of the classes listed above when the condition based on the size variable is met. The issue arises when the value of size is 'md', triggering the first condition. In this scenario, the resulting class in the DOM only displays text-sm instead of px-4 py-2 text-sm.

According to the documentation for ngClass :

keys represent CSS classes that are added if the corresponding expression evaluates as truthy, and removed if falsey

Based on my interpretation:

  • The first condition evaluates to true => the class is correctly applied
  • Subsequently, the second condition evaluates to false => causing px-4 py-2 text-base to be removed from the class list, leaving only text-sm.

While I believe I comprehend the issue at hand, being new to Angular, I would appreciate any guidance on effectively utilizing ngClass. Is there a solution available to address this matter?

Answer №1

To incorporate the shared classes into your usual class declaration, simply follow this format:

<button
    [ngClass]="{
      'text-sm': size === 'md',
      'text-base': size === 'lg',
    }"
   class="px-4 py-2"
  >
    My Button
  </button>

Answer №2

Want to apply multiple conditions like this? Check it out:

[ngClass]="property  === value1 ? 'css-class-name1' : property  === value2 ? 'css-class-name2' : property  === value3 ? 'css-class-name3' :   'default-css'"

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

Encountering an issue upon launching the application: "Error: Token is required in order to proceed!"

I encountered the following error. Can someone please point out what's causing it? How can I resolve this issue? Could there be something missing in main.ts? Error: (index):39 Error: Error: Token must be defined! at new BaseException (https:/ ...

Adding Bootstrap component via ajax request

I'm facing an issue with injecting a Bootstrap component using ajax. I usually include a select element like this: <select class="selectpicker" data-width="75%"> Most of the HTML code is generated dynamically through javascript, which you can ...

Issue with Mongoose $in operator causing updates to only affect a single document

Having some issues with the "$in" operator in Mongoose. I have a User schema that includes an array of Card schema. The Card schema contains a 'score' field that I want to update based on a list of Card ids. Here's what I have attempted: Us ...

Show either the abbreviated or complete form of the text

Initially, the default display should show the shortened version of each element (one line with "..." included). All items must consistently be shown in either the shortened or full-length version. If all items are in shortened mode - clicking on one item ...

Setting a default value for a select-option in Angular can be done by initializing the

How can I set a default value of 'John' for a select option in the ngOnInit function when the page loads? I'm not entirely sure if I'm using the select option correctly. Please let me know if there's an error in my approach. I att ...

What is causing ngResource to change the saved object to something like "g {0: "O", 1: "K", ..} once it receives a response?

In my current setup, I have a default ngResource that is defined in the following way: var Posts = $resource('/posts/'); Once I retrieve a blog post from my nodejs server using the code below: $scope.post = Posts.get({_id:query._id}); The use ...

"Creating Interactive Slider Bullets: A Guide to Linking them to Their Respective

I can't seem to figure out how to connect my slider bullets to my slider slides. I want bullet 1 to correspond to slide 1, bullet 2 to slide 2, and so on. It should be a simple task, but I'm struggling to make it work. I have set up a basic reset ...

What is the best way to find a match for {0} while still allowing for proper

I am working on developing a text templating system that allows for defining placeholders using {0}, similar to the functionality of .Net's string.format method. Here is an example of what I am aiming for: format("{0}", 42), // output ...

What is the best way to simultaneously utilize two APIs where one is using HTTP and the other is using HTTPS?

What is the best way to simultaneously use two APIs, one being http and the other https, in Angular or JavaScript? ...

Context failing to refresh value upon route changes

My current context setup is as follows: import { createContext, ReactNode, useState } from "react"; type props = { children: ReactNode; }; type GlobalContextType = { name: string; setName: (value: string) => void; }; export const Glob ...

Executing a function by click event using the onclick attribute from a file located in the public directory of my project (Next

I'm new to using Next.js and I have a question about how to utilize onclick to execute a function from an external file located in my public folder. Below is my index.js file: import Head from "next/head" import Script from "next/scrip ...

flylatex is struggling to locate some modules

When I try to run flylatex from github on Debian and Ubuntu, I encounter the following Error. I'm not sure if there's an issue with my nodejs setup or if flylatex itself has an error. To troubleshoot, I initially ran npm install -d in the working ...

How can I efficiently retrieve the "value" of a cookie and store it in a .txt file using Python?

Seeking to automate certain requests, I am currently using selenium's get_cookie function to extract cookies from a website. The retrieved cookie data is returned as a dict structured like this: {'domain': 'website-name-here', &a ...

Is there a way to determine if a React functional component has been displayed in the code?

Currently, I am working on implementing logging to track the time it takes for a functional component in React to render. My main challenge is determining when the rendering of the component is complete and visible to the user on the front end. I believe t ...

In Angular, ensure validation for dropdowns is enforced when the selected value is "yes" in the 2nd dropdown. This means that validation must be applied to the

I am currently working on validation for a set of dropdown menus. There are three dropdowns in total: 1) The first and second dropdowns are mandatory, but for the third dropdown, I need to implement a logic. The logic is that if the value of the second d ...

How can I toggle the radio button based on the dropdown selection?

I'm attempting to enable or disable a radio button based on the selection from a dropdown menu. View my jsfiddle example here For example, if the user selects "persons" from the dropdown, only the options for Anthony and Paul should be available to ...

Unexpected behavior observed with Async/Await

I am currently learning how to use Async/Await, which is supposed to wait until the Await function finishes executing before moving on with the code. However, I have encountered an issue where my code stops completely after using Await. Here is the method ...

Tips for modifying and refreshing data in a live table with JQuery

One challenge I'm facing is figuring out how to transfer the data from a dynamic table back into input fields when clicking on the edit button of a specific row. Additionally, I need to update that particular row based on any changes made to the value ...

instructions for transferring image filenames to a database with the help of multer and express

While utilizing multer and express to upload a photo, everything appears to be functioning correctly. However, I am encountering issues with sending the image name to the mongoose database. The images are successfully uploaded to the upload directory. Alt ...

Develop a personalized conditional rendering directive in Vue.js

I am exploring how to create a custom Vue conditional directive. While I could simply use a global method and call it within a v-if, I prefer the idea of having a dedicated directive for clarity in my code. My objective is to apply this directive to an el ...