Updating CSS classes based on conditions in Angular 2

I have a view with three buttons, and initially the content of the first button is displayed. When a button is clicked, it becomes active, but on page load, the initial button does not have the active state. To set the first button as active upon page load, I added the following to the div:

[ngClass]="'active'" 

The issue now is that when another button is clicked, the first button remains active. The data displayed depends on a string value. As each button is clicked, the string changes.

How can I implement a condition to check for the current string? For example, if the string matches the current data being displayed, then add the active class to that specific button?

This is what I am looking for in terms of syntax:

[ngClass]="'active'" if "myString == ThisIsActiveString;

However, the class is not added correctly using this syntax in my current button code:

<button  [class.active]="shown == EQUIFAX" (click)="shown = 'EQUIFAX'" type="button" id="equifax" class="btn btn-secondary">Equifax Report </button>

Just to clarify, the string is initially set to "EQUIFAX" on page load.

Here is an example based on the provided solution:

<button [ngClass]="'active' : shown == 'EQUIFAX'" (click)="shown = 'EQUIFAX'" type="button" id="equifax" class="btn btn-secondary">Equifax Report </button>

Answer №1

Conditional CSS classes can be dynamically added using the NgClass directive like this:

[ngClass]="{ 'active': myString == conditionString }";

For more information on how to use the NgClass directive and to see examples, visit this link.

Answer №2

When you write

[class.active]="shown == EQUIFAX"
, you are comparing the value of shown to a variable called EQUIFAX.

To make this comparison with a string instead, you should change it to

[class.active]="shown == 'EQUIFAX'"

If you use [ngClass], the syntax would be

[ngClass]="{'active': shown == 'EQUIFAX'}

You can see this in action in the following playground: http://plnkr.co/edit/j2w8aiQPghl0bPZznoF2?p=preview

Answer №3

To include multiple classes and specify two or more conditions, you can add each class and condition separated by a comma.

Here is an example:

[ngClass]="{'first-class': condition,
            'second-class': !condition}"

Answer №4

Here is a way to achieve that:

[className]="myString === activeString";

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

Can you determine the base class type based on the derived class?

I've encountered a typings issue while working on a new feature for my TypeScript library. Let's dive into the problem with the following example: class Base { ... } class User extends Base { ... } class Product extends Base { ... } class Comp ...

Avoid displaying the value in Ant Design's autocomplete feature

Can someone assist me with clearing the auto complete placeholder or displaying only part of the label instead of the value after a user selects from a drop-down list? The current setup shows the unique ID as the value, which we want to keep hidden from en ...

disabling tabs that are next to each other using react hooks

When the user clicks on item one button in the first tab, it should disable the next two tabs. If the user clicks it back, it should enable the other two tabs. The same functionality should apply to the other tabs as well. Currently, I have disabled the ...

Express server for an Angular 2 application failing to handle API requests

My angular2 application is currently hosted on Heroku using a Node/Express server. For example, when the app makes an API call to retrieve posts at appurl.com/posts, it is structured as appurl.com/api/posts. All API calls are made at appurl.com/api/~wha ...

How can I convert a string into JSON format in Node.js?

Imagine this scenario: a HTTP REST API has just sent me a JSON in the form of a string. How can I transform it back into a structured JSON object? ...

Is there a way to identify when a Tween.js animation has completed?

Is there a completed or finished event available when using this code for animating the camera in a scene with tween.js? tween : function (target){ var position = camera.position; var tween = new TWEEN.Tween(p ...

Angular 2: Creating child routes within a nested routing module

After browsing through a post related to my issue, I found some guidance on routing to a module as a child of another module in Angular 2 RC 5. However, I must admit that I got a bit confused. The post can be found here: How to route to a Module as a child ...

Typescript's complex objects involve a sophisticated and intricate structure in

Just starting out with TypeScript and I'm looking to build a class that describes an object with the following structure: name(string), Array{ "column-name": { "type":"value", " ...

Ways to set each tinymce editor as standard excluding a few selected ones

Currently, I am utilizing TinyMCE as my text editor for a specific project. Within the header of my codebase, I have specified that all <textarea> elements should be rendered with TinyMCE functionality. By default, these text areas have a height of 3 ...

update-post-thumbnail wp-ajax return false

I have been attempting to utilize the media manager within Wordpress. I am using the post editor outside of the admin area, allowing users to create posts with a featured image. I have used the _wp_post_thumbnail_html function to display the image or provi ...

A guide on accessing the first element in an array when performing multiplication within the Interval component in React.js

I am having trouble initiating an if statement from number 0 once the window is loaded, as it seems to be skipping over 0 and starting from 1 instead. Can someone please assist me in understanding how this works? showAnime = () => { let counter ...

I attempted to include multiple images in my HTML using Vue.js, but encountered an error message stating "illegal invocation"

Here is my HTML code: <form method="POST" v-on:submit.prevent="handleSubmit($event);"> <div class="row"> <div class="col-md-4"> <div class="form-group label-floating"> <label class="control-label">Name</label> <input ...

Struggling to connect to an express route?

I'm currently working on a MERN project and I'm encountering a small issue. When trying to make a POST request to a specific route, Express throws a 404 error and tells me that it can't find the desired route. However, everything works perfe ...

Building a RESTful Angular application with unique caching features specifically designed for Microsoft Edge browser

As I develop a Webapp utilizing Angular.js with a RESTful API, I usually work in my preferred browser, Chrome. However, after running tests in Edge, I stumbled upon some intriguing discoveries. I observed that the RESTful server call was returning seeming ...

How do the scopes of a controller and a directive's controller differ from each other?

Can you explain the difference between a controller and a directive's controller in terms of scope? I'm struggling to grasp the distinction and whether it's necessary to create controllers within the DDO for my directives. In the code snipp ...

Enforce numerical input in input field by implementing a custom validator in Angular 2

After extensive research, I was unable to find a satisfactory solution to my query. Despite browsing through various Stack Overflow questions, none of them had an accepted answer. The desired functionality for the custom validator is to restrict input to ...

The reset() function in Angular does not set form controls to empty values

When following the Hero guide, I encountered an issue while trying to reset all fields in the model using the provided code snippet. this.form.reset({ "firstName": "", "lastName": "bzz", "reporter": "" }); The problem arises when only non-empty fi ...

Ensuring ng-multiselect-dropdown validation in Angular 5

I have implemented a multi-select dropdown feature in my application by utilizing the npm package "ng-multiselect-dropdown". As I am working with a template-driven form, I am now looking to add validation for this multiselect functionality. For more infor ...

Is there a way to determine if a property contains a string value?

In my main.js file, I have a function called $scope.onError which is triggered when there is an error while uploading an attachment. The function logs the error message received from the server and assigns it to the variable $scope.errorMessage. If the val ...

Are there more efficient methods than having to include require('mongoose') in each models file?

Is it possible to only require mongoose once in the main app.js file and then pass it to other files without loading it again? Will the script do extra work every time the same module is required? var mongoose = require('mongoose'); I'm wo ...