What is the best way to apply CSS styles conditionally in AngularJS?

Q1. What is the most effective method to modify the appearance of each selected "item" by a user, before pressing the main "delete" button? The aim is to provide immediate visual feedback to eliminate the need for a confirmation dialog box. Users will mark checkboxes to indicate the items they wish to delete. If a checkbox is unchecked, the item should return to its original appearance.

How can CSS styling be applied or removed in this scenario?

Q2. How can I enable users to personalize their viewing experience on my website? This includes selecting from a fixed range of font sizes, customizing foreground and background colors, and more.

What is the best approach to apply the CSS styles chosen/entered by the user?

Answer №1

Angular offers a variety of built-in directives for dynamically manipulating CSS styling:

The typical approach in Angular involves linking a model/scope property to a UI element using ng-model, then associating that property with one of the mentioned directives.

When a user interacts with the UI, Angular automatically updates the associated elements on the page.


Q1 is suited for ng-class where CSS styles can be defined in a class.

ng-class accepts an "expression" that should evaluate to one of these:

  1. a string of class names separated by spaces
  2. an array of class names
  3. a map/object of class names with boolean values

For instance, when displaying items from an array model using ng-repeat and wanting to apply the 'pending-delete' class when a checkbox is checked:

<div ng-repeat="item in items" ng-class="{'pending-delete': item.checked}">
   ... HTML for item display ...
   <input type="checkbox" ng-model="item.checked">
</div>

In this example, we used ng-class expression type #3 - a map/object of class names with boolean values.


Q2 is a good fit for ng-style since the CSS styling is dynamic.

ng-style requires an "expression" that evaluates to:

  1. a map/object of CSS style names to CSS values

For instance, if the user can input a color name into a textbox for the background color:

<div class="main-body" ng-style="{color: myColor}">
   ...
   <input type="text" ng-model="myColor" placeholder="enter a color name">


Fiddle for both scenarios discussed above.

The fiddle also demonstrates ng-show and ng-hide. If a checkbox is checked, the background-color turns pink and some text is displayed. Entering 'red' in the textbox hides a div.

Answer №2

Encountered issues arise when adding classes within table elements while having a class already applied to the entire table (such as a color applied to odd rows

<myClass tbody tr:nth-child(even) td>
). Upon inspecting the element using Developer Tools, it appears that no styles are assigned in element.style. To address this, instead of utilizing ng-class, I opted for ng-style, where the new CSS attribute is visible inside element.style. Here's the code snippet that proved effective for me:

<tr ng-repeat="element in collection">

    [...amazing code...]

    <td ng-style="myvar === 0 && {'background-color': 'red'} ||
                  myvar === 1 && {'background-color': 'green'} ||
                  myvar === 2 && {'background-color': 'yellow'}">{{ myvar }}</td>

    [...more amazing code...]

</tr>

Myvar undergoes evaluation, determining the style to be applied to each <td> based on the value of myvar, overwriting the existing style applied by the CSS class for the entire table.

UPDATE

To apply a class to the table under specific conditions, such as upon visiting a page or other scenarios, you can utilize this structure:

<li ng-class="{ active: isActive('/route_a') || isActive('/route_b')}">

The key to activating an ng-class lies in specifying the class to apply along with a true or false statement. A true value applies the class, while false does not. In this example, two route checks are made with an OR between them, ensuring that if we are in either /route_a or route_b, the active class will be applied.

This approach functions based on a logic function that returns either true or false.

In the initial example, ng-style is conditioned by three statements. If all are false, no style is applied. However, at least one statement will evaluate to true, leading to the application of the corresponding style. As any non-empty array equates to true, the resulting array will have only one true value, ultimately applying the remaining style due to the usage of OR in the overall response.

Additionally, let me provide you with the isActive() function:

$rootScope.isActive = function(viewLocation) {
    return viewLocation === $location.path();
};

NEW UPDATE

Here's a handy tip for applying a class based on a variable's value, like displaying different icons depending on the content within a div. The following code proves beneficial, especially in ng-repeat situations:

<i class="fa" ng-class="{ 'fa-github'   : type === 0,
                          'fa-linkedin' : type === 1,
                          'fa-skype'    : type === 2,
                          'fa-google'   : type === 3 }"></i>

Icons sourced from Font Awesome

Answer №3

When ng-class cannot be utilized, such as when styling SVG elements, this method works effectively:

ng-attr-class="{{someBoolean && 'class-when-true' || 'class-when-false' }}"

(It may require the latest unstable version of Angular to use ng-attr-, I am currently using 1.1.4)

An article discussing working with AngularJS and SVG has been published by me. It addresses this particular issue along with several others. http://www.codeproject.com/Articles/709340/Implementing-a-Flowchart-with-SVG-and-AngularJS

Answer №4

span class="circle circle-{{selectcss(document.Extension)}}">

Here is the code snippet:

$scope.selectcss = function (data) {
    if (data == '.pdf')
        return 'circle circle-pdf';
    else
        return 'circle circle-small';
};

The CSS styles are provided below:

.circle-pdf {
    width: 24px;
    height: 24px;
    font-size: 16px;
    font-weight: 700;
    padding-top: 3px;
    -webkit-border-radius: 12px;
    -moz-border-radius: 12px;
    border-radius: 12px;
    background-image: url(images/pdf_icon32.png);
}

Answer №5

Following this advice made a significant impact on my situation

<a ng-style="{true: {marginLeft: '30px'}, false: {}}[deleteTriggered]">...</a>

Answer №6

One way to implement conditional styling is by using a ternary expression. Here are two methods to achieve this effect:

<div ng-style="myVariable > 100 ? {'color': 'red'} : {'color': 'blue'}"></div>

Alternatively, you can also use the following approach:

<div ng-style="{'color': (myVariable > 100) ? 'red' : 'blue' }"></div>

Answer №7

If you're looking for a quick and easy way to apply CSS styles with just one or two properties, consider this option:

Here's how it works:

<tr ng-repeat="element in collection">
    [...add your own code here...] 
    <td ng-style="{'background-color': getTrColor(element.myvar)}">
        {{ element.myvar }}
    </td>
    [...add more of your code here...]
</tr>

And here's the corresponding controller code:

$scope.getTrColor = function (colorIndex) {
    switch(colorIndex){
        case 0: return 'red';
        case 1: return 'green';
        default: return 'yellow';
    }
};

Answer №8

Take a look at this example

<!DOCTYPE html>
    <html ng-app>
    <head>
    <title>Example of Conditional CSS Class Changes with AngularJS</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
    <script src="res/js/controllers.js"></script>

    <style>

    .checkboxList {
        border:1px solid #000;
        background-color:#fff;
        color:#000;
        width:300px;
        height: 100px;
        overflow-y: scroll;
    }

    .uncheckedClass {
       background-color:#eeeeee;
       color:black;
    }
    .checkedClass {
        background-color:#3ab44a;
        color:white;
    }
    </style>

    </head>
    <body ng-controller="TeamListCtrl">
    <b>Teams</b>
    <div id="teamCheckboxList" class="checkboxList">

    <div class="uncheckedClass" ng-repeat="team in teams" ng-class="{'checkedClass': team.isChecked, 'uncheckedClass': !team.isChecked}">

    <label>
    <input type="checkbox" ng-model="team.isChecked" />
    <span>{{team.name}}</span>
    </label>
    </div>
    </div>
    </body>
    </html>

Answer №9

AngularJS version 1.2.0rc introduced issues with ng-class and ng-attr-class when used with SVG elements. Previously, these directives worked fine, even with regular binding inside the class attribute.

Unfortunately, none of the following methods work anymore:

ng-class="current==this_element?'active':' ' "
ng-attr-class="{{current==this_element?'active':' '}}"
class="class1 class2 .... {{current==this_element?'active':''}}"

To workaround this problem, I have resorted to using

ng-attr-otherAttr="{{current==this_element?'active':''}}"

and then applying styles using

[otherAttr='active'] {
   ... styles ...
}

Answer №10

In the near future, a new method for applying styles conditionally is emerging - through the use of scoped styles.

<style scoped type="text/css" ng-if="...">
</style>

Currently, only Firefox supports scoped styles, but this may change as more browsers adopt this feature.

Answer №11

Recently, I stumbled upon a new method that could be quite beneficial for some individuals. This approach allows you to modify a CSS rule within a style element without the need for repetitive angular directives like ng-style, ng-class, ng-show, ng-hide, ng-animate, and others.

The technique involves utilizing a service with variables set by a controller and monitored by an attribute-directive named "custom-style". The versatility of this strategy opens up various possibilities, and I have provided some general advice along with a working example on this link.

var app = angular.module('myApp', ['ui.bootstrap']);
app.service('MainService', function(){
    var vm = this;
});
app.controller('MainCtrl', function(MainService){
    var vm = this;
    vm.ms = MainService;
});
app.directive('customStyle', function(MainService){
    return {
        restrict : 'A',
        link : function(scope, element, attr){
            var style = angular.element('<style></style>');
            element.append(style);
            scope.$watch(function(){ return MainService.theme; },
                function(){
                    var css = '';
                    angular.forEach(MainService.theme, function(selector, key){
                        angular.forEach(MainService.theme[key], function(val, k){
                            css += key + ' { '+k+' : '+val+'} ';
                        });                        
                    });
                    style.html(css);
                }, true);
        }
    };
});

Answer №12

One recommended approach would be to validate a condition in your controller using a function that returns either true or false.

<div class="week-wrap" ng-class="{today: getTodayForHighLight(todayDate, day.date)}">{{day.date}}</div>

Then, within your controller, verify the condition with the following code:

$scope.getTodayForHighLight = function(today, date){
    return (today == date);
}

Answer №13

Keep an eye out for this: if the CSS style includes dashes, be sure to eliminate them. For example, if you're trying to define the background-color, the proper syntax would be:

ng-style="{backgroundColor:myColor}" 

Answer №14

Learn how I dynamically add a gray text style to a disabled button

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  styleUrls: [ './app.component.css' ],
  template: `
  <button 
    (click)='buttonClick1()' 
    [disabled] = "btnDisabled"
    [ngStyle]="{'color': (btnDisabled)? 'gray': 'black'}">
    {{btnText}}
  </button>`
})
export class AppComponent  {
  name = 'Angular';
  btnText = 'Click me';
  btnDisabled = false;
  buttonClick1() {
    this.btnDisabled = true;
    this.btnText = 'you clicked me';
    setTimeout(() => {
      this.btnText = 'click me again';
      this.btnDisabled = false
      }, 5000);
  }
}

Check out the live demo here:
https://stackblitz.com/edit/example-conditional-disable-button?file=src%2Fapp%2Fapp.component.html

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

Is BEM mandating the creation of superfluous elements?

<header> <a href="#"><img src="kitty.jpg" /></a> ... </header> In the context of organizing for BEM, take this example within the header section that is not dependent on the header block. To adhere to BEM guidelines, I op ...

Requirements for using Angular JS and Node JS

With upcoming projects involving AngularJS and Node.js, I'm a bit apprehensive as I don't have much experience with JavaScript. Should I start by picking up a book on each technology, or is it essential to learn more about JavaScript first before ...

Choose a HTML element <a> containing a hyperlink reference and a nested child element <li>

Does anyone know of a way in javascript/css to select the (n) <li> in my code, while also specifying that the <li> must have a parent with the current <a> tag containing a specific href link? <a href="www.link.com">CATEGORY NAME& ...

The element will only show up upon resizing (in Safari web browser)

I am facing a problem with a button styled using the class btn-getInfo-Ok <button class="btn-getInfo-Ok">Hello</button> in my style.css file .btn-getInfo-Ok { color:white !important; margin: 0 auto !important; height:50px; bottom:0; ...

Unable to include links to other HTML pages in my MEAN Stack Application

Recently, I've been diving into tutorials on how to build a Mean stack application. So far, I've successfully created a single-page application. However, when attempting to link multiple HTML pages other than the index.html, I keep encountering i ...

Incorporating a variety of images into this hexagonal design framework

Hello there! I am just starting to learn CSS and HTML, and I have a question. Is it possible for me to use the same CSS styling but have different images inside each of the hexagons? I want to replace the image '' with multiple images without rep ...

Unable to access the latitude property as it is undefined

I am completely puzzled by the appearance of this issue. This snippet shows my Google Map script: <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places,geometry"></script> Below you can see that I have defined lat ...

You are only able to click the button once per day

I am working on a button that contains numeric values and updates a total number displayed on the page when clicked. I would like this button to only be clickable once per day, so that users cannot click it multiple times within a 24 hour period. Below i ...

What is the best way to navigate to Amazon URLs with BeautifulSoup4?

Problem: The list "linkElems" seems to be empty Suspected Cause of Issue: I believe the tags I am specifying to retrieve are incorrect Purpose of Program: Execute a search on Amazon.com via command line arguments and save the website data in the variab ...

Averages of window sizes visible without scrolling

Most designers target browsers with a resolution of 1024x768, although widths of 960 - 980px are also acceptable. (Personally, I prefer 960 for the chrome, but that's just my preference.) My query is - what window height can we generally assume for u ...

What is the best way to vertically center text within a selection box? (This is not referring to a select box or a div box)

While assigning a line-height to text elements like div, span, or p and dragging them in the browser, an unsightly empty space appears within the selection box: https://i.sstatic.net/Ws08H.png I am seeking a way to elevate the actual text content within ...

Why are you leaving a trail of timestamps in your .css files?

Within certain source codes, I have observed the following: <link rel="stylesheet" href="/css/style.css?201007071609" type="text/css" /> This prompts my question: What is the purpose behind appending 201007071609 to style.css in the code snippet ab ...

Sending data from an Ionic application to a server

I came across this solution on a forum, but it lacks detailed explanation for me to customize it according to my requirements. The author also mentions a stack overflow question, which led to various "different" solutions leaving me feeling confused. Belo ...

How can I use CSS to place a div at the bottom of its container?

I am trying to figure out how to use CSS to position a div at the bottom of its container, but the size of the container is not fixed. Can anyone provide some guidance on this issue? Thank you in advance for helping me solve this problem. You can check o ...

Is there a way to modify the font color in Chrome when the input autofill feature is active?

I tried adding the css code below: input:-webkit-autofill{ color:white; } Unfortunately, it didn't have any effect. If anyone can assist me with this issue, I would greatly appreciate it. Thank you. ...

Tips for using CSS to adjust the width of a parent element based on the width of an image

I'm currently working on developing my own lightbox using React, and I am looking to adjust the width of a div with the class .lightbox-active based on the width of the image it contains. Right now, I have set the parent element to have a max-width: 5 ...

Encountering difficulty loading a Laravel project due to an error

I encountered an issue with the master.blade.php file located in the views folder. The error message reads as follows: *<br/>ParseError <br/>syntax error, unexpected '{', expecting ')' (View: E:\soft\Xampp2\h ...

What is the best way to refresh the content in a table on all HTML pages?

I'm a new developer with a website that includes over 100 pages, each containing HTML tables. Is there a way to update all table content at once without manually editing every single page? All pages have links inserted in the table that need to be u ...

Scrolling the page with AngularJS after revealing hidden elements using ng-show

Currently faced with a challenge involving a list of hidden items that I need to show and scroll to with just one click. Here is the code snippet for reference: http://plnkr.co/edit/kp5dJZFYU3tZS6DiQUKz?p=preview Upon inspecting the console, it seems that ...

Font Awesome fails to load when internet connection is lost

Utilizing font-awesome icons to enhance my HTML and CSS templates has been great. However, I have encountered an issue where the icons disappear when I download the CSS file and include it in my pages. Online Path : <link href="http://netdna.bootstrapc ...