Adding or changing class in Angular 2 based on specific conditions

Currently, my focus is on building a web application using Angular and the Semantic-UI framework.

In order to add a single class to an element based on a specific condition, I have successfully implemented the following syntax:

[class.className]='condition'

However, I am now faced with a situation where I need to apply multiple class names to an element, and I am unsure of the correct approach to take.

To address this issue, I attempted to utilize ngClass by referencing a Plunker example found here. Unfortunately, the provided solution did not yield the desired results.

My question now is, how can I modify my Plunker to achieve the desired functionality?

Answer №1

To create a string with multiple classes, you can utilize the [ngClass] directive here.

<div [ngClass]="('firstClass ' + (active ? 'secondClass' : ''))"></div>

In this scenario, firstClass represents the initial class, while active is a boolean determining the inclusion of the secondClass.

Therefore, in your specific situation, your code could be adjusted as follows:

<div class="field">
    <label for="name">Name:</label>
    <div class="ui input" [ngClass]="((myForm.controls.name.pending ? 'loading' : '') + 'secondClass')">
        <input id="name" [formControl]="myForm.controls.name">
    </div>
</div>

Ensure there are spaces between each pair of class names.

UPDATE

In relation to your plunker example, remember to incorporate the ngClass statement like so:

[ngClass]="[o.order === 'asc' ? 'chevron circle up': '' , o.order === 'desc' ? 'chevron circle down': '']"

Answer №2

If you want to dynamically apply classes in Angular, you can utilize the [ngClass] directive.

<div class="field">
    <label for="name">Name:</label>
    <div class="ui input" [ngClass]="{loading : myForm.controls.name.pending}">
        <input id="name" [formControl]="myForm.controls.name">
    </div>
</div>

When the condition evaluates to true, the specified classes will be added to the element. If the condition is false, the classes will be removed from the element.

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

Guide to defining custom variables from various locations within Angular Js

In my Angular 6 project, I have noticed that in the home.component.ts file, there is a variable being declared at the beginning: public hasResults = false; Then in the home.component.html file, there is a section for displaying this variable: <span st ...

Which ngTagsInput version is recommended for Angular instead of AngularJs?

After discovering the ngTagsInput framework on this site, I found it to be a very comprehensive library. However, for Angular 8 users like myself, I came across the ngx-chips framework on this page. While ngx-chips seems to work, I noticed that it lacks s ...

The 'api' property is not found within the 'MyService' type declaration

Currently, I am working on a tutorial where we are building an Angular service to send emails from a form using the Mailthis Email API. In the code for the service, I encountered an error related to the 'api' variable that states "Property ' ...

jQuery mobile enhancing user experience with dynamic background images

I am having trouble setting different background images for each page in jQuery Mobile. <div data-role="page" id="pageone">... </div> <div data-role="page" id="pagetwo">... </div> Since each page has a unique ID, I tried ...

Tips for executing numerous asynchronous tasks in Ionic 3 and closing a loader once all tasks are completed

Currently, I am in the process of developing an Ionic 3 application that offers the feature to cache a list of articles content on demand. The implementation involves utilizing Storage which employs promises for its operations. The code snippet I have wri ...

Pressing the button in the navigation bar results in an expansion of the navbar

Can someone help me figure out why my navbar's height is different from the example on this Bootstrap navigation bar snippet? Here's the code I used: https://www.w3schools.com/bootstrap4/tryit.asp?filename=trybs_navbar_form&stacked=h I copi ...

Utilizing the CSS properties of table-cell and float in a display

I've designed a header section, but I'm facing an issue. It looks good on devices with resolutions greater than 1020: https://i.sstatic.net/VlgmR.png https://i.sstatic.net/x3V15.png The problem arises on smaller resolutions: https://i.sstatic. ...

What is the specific use of the second app.css file in Laravel?

I'm currently delving into Laravel 8, and I'm perplexed by the role of Resources\css\app.css. While every other component in the Resources directory serves a clear function, the app.css file appears to be empty. Even when I attempt to a ...

What is the best way to move an element from a relative to an absolute position smoothly?

I've been working on my portfolio site and came up with a unique idea for the landing page – having the name placed in the center and then transitioning into a navbar when a route is selected. However, I'm facing a dilemma. To achieve this eff ...

Sorting custom folders and files in an Angular Material table is a breeze with this handy feature

In my mat-table, I have a mix of Files and Folders that need to be sorted similar to Microsoft's file explorer. Folders should not be separated from other folders, and the same rule applies to files. All other sorting rules should remain unchanged. ...

Adjust the positioning of the share section to take up the entire width on mobile devices, while displaying differently

When attempting to position my share div to occupy the full width of one of its sibling (person) elements, I encountered some issues. The share div is designed to only display when a button is clicked. You can view the live version and see the problem by ...

Ways to trigger a function in Angular every 10 seconds

What is the method to utilize Observable function for fetching data from server every 10 seconds? Custom App service fetchDevices (): Observable<Device[]> { return this.http.get(this.deviceUrl) .map(this.extractData) .catch(this ...

creating a gap between two links within a div element

I have a dilemma regarding the spacing between two hyperlinks within a div tag. Can anyone advise on how to create this space effectively? .btn-filter { background-color: #ffffff; font-size: 14px; outline: none; cursor: pointer; height: 40px ! ...

Increasing the font size of the mdToolTip in Angular2 Materials

Recently, I've been trying to adjust the font size in mdToolTip. While looking through the pre-themes CSS, I came across this class: .mat-tooltip { background: red; font-size: 50px; } However, it seems to be ignoring the font-size syntax. Can any ...

Encountering an error while trying to run ng serve following ng build

Currently working on my initial Angular application, I am in the process of setting up an existing Angular app on my local machine. Encountered the following error message when running ng serve ERROR in src/app/common-componets/directives/dropFile/d ...

Position the text at the top edge of the image

Greetings, I have the following images: My goal is to achieve this look: I have floated the flags to the right and set individual images to float left in my CSS style. However, I am struggling to add text-boxes on top of the images. Any tips or suggesti ...

Closing iframe in Angular 4 after redirection

I am currently working on an Angular 4 application that involves integrating a third-party payment system called Tranzila. Tranzila offers a convenient integration method using an iframe, allowing users to make payments on their domain without me having to ...

Guide to changing the class of a particular child element when the parent element is clicked with vanilla JavaScript

Upon clicking the parent button, a class within its child element will toggle to show or hide. If the child element is selected, a loading animation will appear for a brief moment before reverting back to its original hidden state. I attempted to achieve ...

Enhance the user experience by adding visual appeal to the first option in the selection form. Make it

Is there a way to change the color of the first option in the selection box to grey, similar to the example above? Additionally, how can I create a clickable icon that will display all options? The current setup is not functioning correctly. <div clas ...

"Exploring the world of Typescript code through the eyes of Chrome with the help of the

Currently, I am immersing myself in learning Angular2 by following along with this project: https://github.com/start-angular/angular2-node-socket-io-chat-app I am utilizing VS Code and the Debugger for Chrome. However, when attempting to debug the code an ...