The functionality of ngClass fails to toggle the value appropriately when utilizing an object within a component

When implementing the code below to toggle the class, everything runs smoothly

<p [ngClass]="idPresent ? 'alert alert-success' : 'alert alert-danger'">
  Working
</p>

After changing the value of IdPresent in the component, I observe the correct class being applied,

However, when I use an object in the component for the same purpose, it only functions properly if idPresent is set to false. If I switch idPresent to true, the code provided fails to apply the right class.

<p [ngClass]="idValueClass">
   Not working
</p>
public idPresent = false;
 
public idValueClass = {
  "alert alert-success" : this.idPresent,
  "alert alert-danger"  : !this.idPresent
};

Could someone assist me in understanding what mistake I might be making?

Update:

I modify the value of idPresent once I receive a response from the REST API call

 ngOnInit(): void {
 this.http.get('http://localhost:8083/v1/uniqueid', {
  headers: {'Authorization':'Basic dXNlcjpwYXNzd29yZA=='}
 })
 .subscribe(response => {
    if(response) {
      console.log(response)
       this.serverId = response;
       this.idPresent = true;
    } else {
       this.idPresent = false;
    }
    console.log("idPresent : " + this.idPresent)
 })

}

Once the server responds, I can observe the updated value in the console.

Answer №1

In Angular versions 16 and 17, we have the option to utilize signals as pointed out by @Yong Shun.

Here is an example of how to implement this:

public idPresent = signal(false);

public idValueClass = computed(() => ({
  alert: true,
  'alert-success': this.idPresent(),
  'alert-danger': !this.idPresent(),
}));

onClick() {
  this.idPresent.update(value => !value);
}

It's important to note that in the .html file, we need to replace idPresent with idPresent(), and idValueClass with idValueClass().

<p [ngClass]="idValueClass()">
  Not working
</p>
Current idPresent: {{ idPresent() }}

You can view a demo on StackBlitz, which was adapted from Yong Shun's StackBlitz project.

NOTE: In the StackBlitz demo, I used

changeDetection:ChangeDetectionStrategy.OnPush
, but please be aware that when a signal is updated, Angular refreshes the entire view.

Answer №2

It appears that the issue you mentioned involves the removal of the "alert" class.

According to the information provided in the documentation,

Object - keys are CSS classes that get added when the expression given in the value evaluates to a truthy value, otherwise they are removed.

This means that if the last "alert" was false, it will be removed from the class list.

To address this, update the idValueClass as follows:

public idValueClass = {
  alert: true,
  'alert-success': this.idPresent,
  'alert-danger': !this.idPresent,
};

View Demo on StackBlitz


Update:

As pointed out by @Eliseo, if there is a button or logic to update the idPresent, the changes may not automatically reflect in the idValueClass.

A trigger/change event is necessary to update the idValueClass accordingly.

<button class="btn btn-primary" (click)="onClick()">Update</button>
onClick() {
  this.idPresent = !this.idPresent;
  this.idValueClass = {
    alert: true,
    'alert-success': this.idPresent,
    'alert-danger': !this.idPresent,
  };
}

Alternatively, you can implement a getter for idValueClass (although it is not recommended, see: Getter and setter in templates is a bad idea)

Answer №3

I've encountered this issue before, where key names like "success", "alert", "warning" can be hidden with the same case. I attempted to create a single name class ("alert-success") instead of multiple classes ("alert alert-success").

You can test the following code:

enter code here

public idValueClass = {
  'alert': true,
  'alert-success': this.idPresent,
  'alert-danger': !this.idPresent,
};

I recommend using ternary conditions in ngClass for more flexibility in getting values in .ts files.

idValueClass() {
  return this.idValueClass ? 'alert alert-success' : 'alert alert-danger'
};

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

Styling input groups with box shadows in Bootstrap 4

One issue I am encountering is the focus shadow that appears when the input text is focused. My goal is to have both the text input and the right button display a focus border. To illustrate this problem, I have created a JSfiddle: http://jsfiddle.net/a5u ...

A guide on capturing the text content of the error message from the <mat-error> element with Protractor

I have encountered an element that is giving me trouble in retrieving the error message text into a variable. <mat-error _ngcontent-c16="" class="mat-error ng-star-inserted" id="error-email-required" role="alert" ...

When using percentages in HTML, the height and width of a background picture may not scale correctly

Currently, I am utilizing Webstorm software purely for HTML and CSS without any additional plugins. In my code, there is a <section> element that only has the <html> and tags as its parent elements. This particular section is assigned an ID th ...

Dropdown within Datatable does not automatically select the bound option [PrimeNG]

Hey there! I'm a trainee just entering the world of frontend development, so apologies in advance if my question seems silly or if my code looks messy (any corrections are greatly appreciated). In my project, I have a Dropdown element inside a Datata ...

The Angular user interface is failing to update in accordance with the list obtained from the HTTP GET request made to the .Net Core API

Currently, I am working on an application that utilizes Angular for the frontend and .Net Core API 3.0 for the backend. My objective is to display a list of clients using the Angular Material grid. In my OnInit() method, I invoke my getAllClients service t ...

Utilizing conditional styling in React: the ability to add or attach CSS classes based on

Is there a more efficient way to implement conditional formatting for this scenario? const PaginationStorePageLink = ({ store, pageNum }) => (observer(({ PaginationStore }) => { const className = this.props.store.currentPage === this.props.pageNum ...

I found that the Angular checkbox was only allowing me to select one value at a time instead of

Hey there, I am currently working on an angular tickbox where I want to be able to tick multiple values. However, I am facing an issue where only the latest checkbox value is displayed instead of both English and German together. How can I populate data fr ...

Seeking assistance with rearranging items using flexbox when transitioning between portrait and landscape mode

Check out the wireframe below to see how our page currently appears in landscape mode, along with the items it contains: View landscape wireframe here Below is the corresponding code for the landscape wireframe: <div class="wrapper"> &l ...

cdkDropList does not function properly when used with ng-template in a dynamic component list

Exploring the new Drag&Drop features introduced in Angular Material 7, I am dynamically generating components using ng-template. <div cdkDropList (cdkDropListDropped)="dropLocal($event)"> <ng-template #components></ng-templat ...

Fade In/Out Scroll Effect

As the user scrolls down the page, I have a slider that smoothly slides from right to left. What I'm trying to achieve is for the slider to fade out when the last slide is no longer in view during downward scrolling, and fade back in as the last slid ...

Optimized Image Loading with Angular17's ngSrc

Currently experimenting with Angular 17: // typescript get getWidth(): number { // this._el is an inject(ElementRef); const width = +this._el.nativeElement.querySelector( '[id="fs-img-container"]' ).clientWidth; ...

The dropdown will close automatically when the user clicks outside of it

My dropdown setup requires it to close when the user clicks outside of it. <div [class.open]="qtydropdownOpened"> <button (click)="qtydropdownOpened = !qtydropdownOpened" type="button" data-toggle="dropdown" aria-haspopup="true" [att ...

Is it possible to iterate through div elements using .each while incorporating .append within an AJAX call?

After sending AJAX requests and receiving HTML with multiple div elements (.card), I am using .append to add new .card elements after each request, creating an infinite scroll effect. However, I am facing issues when trying to use .each to iterate over all ...

Is it possible that the div's height is not being set to 0 pixels

<div style="height:0px;max-height:0px"> </div> It appears that setting the height of a div to 0 pixels is not having the desired effect. The div is still expanding to display its contents, so how can we stop this from occurring? ...

Responsive Bootstrap tables nested within responsive tabs

Utilizing footable in conjunction with Boostrap Responsive Tabs leads to an issue post-resize. When the page is initially loaded on a desktop, everything functions properly until the screen is resized. Once the screen is resized, the tables within the tabs ...

Struggling to position CSS div in the middle of computer screen

I have created a main login div that is always displayed in the middle of the screen. However, I also have two additional divs - one that is supposed to show above the login div and the other below it. While the login div displays perfectly in the middle ...

Text in the middle of a button

I've been attempting to recreate the design of this "subscribe to the newsletter button". I'm struggling with achieving the white "inside border or outline" effect. Here is an example of the button ...

How can I restrict the number of items displayed in each row within a navigation submenu flexbox?

My primary navigation menu has numerous child items, and I want to ensure they remain visually appealing and organized. To achieve this, I am aiming to limit each row of submenu items to only 4. After researching other solutions online, I attempted adding ...

What is the best way to flip the direction of the text input for a Calculator?

I am currently working on creating a basic calculator from scratch using HTML, CSS, and JavaScript. I have been trying to figure out how to align the numbers to the right side of the input element. Can anyone provide me with guidance on how to achieve thi ...

What causes the Object expected error in jQuery?

Looking for a way to demo horizontal collapse pane with a simple web page that includes html, css, and jquery. <html> <head> <script type="text/javascript" src="//code.jquery.com/jquery-1.10.1.js"></script> <title>Sa ...