How to Conditionally Apply CSS Styles in Angularjs

How do I conditionally apply CSS styles in AngularJS?

Angular provides a number of built-in directives for manipulating CSS styling conditionally/dynamically:

  • ng-class - use when the set of CSS styles is static/known ahead of time
  • ng-style - use when you can't define a CSS class because the style values may change dynamically. Think programmable control of the style values.
  • ng-show and ng-hide - use if you only need to show or hide something (modifies CSS)
  • ng-if - new in version 1.1.5, use instead of the more verbose ng-switch if you only need to check for a single condition (modifies DOM)
  • ng-switch - use instead of using several mutually exclusive ng-shows (modifies DOM)
  • ng-disabled and ng-readonly - use to restrict form element behavior
  • ng-animate - new in version 1.1.4, use to add CSS3 transitions/animations

The normal "Angular way" involves tying a model/scope property to a UI element that will accept user input/manipulation (i.e., use ng-model), and then associating that model property to one of the built-in directives mentioned above.

When the user changes the UI, Angular will automatically update the associated elements on the page.


Q1 sounds like a good case for ng-class -- the CSS styling can be captured in a class.

ng-class accepts an "expression" that must evaluate to one of the following:

  1. a string of space-delimited class names
  2. an array of class names
  3. a map/object of class names to boolean values

Assuming your items are displayed using ng-repeat over some array model, and that when the checkbox for an item is checked you want to apply the pending-delete class:

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

Above, we used ng-class expression type #3 - a map/object of class names to boolean values.


Q2 sounds like a good case for ng-style -- the CSS styling is dynamic, so we can't define a class for this.

ng-style accepts an "expression" that must evaluate to:

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

For a contrived example, suppose the user can type in a color name into a texbox for the background color (a jQuery color picker would be much nicer):

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


Fiddle for both of the above.

The fiddle also contains an example of ng-show and ng-hide. If a checkbox is checked, in addition to the background-color turning pink, some text is shown. If 'red' is entered in the textbox, a div becomes hidden.

Applying CSS style conditionally in ng-repeat in AngularJS

You would do this using the ng-class directive. You'll simply add your styling as a class in your stylesheet and change your angular code to this:

<tr ng-repeat="data in userList" 
ng-class="{ 'my-css-class': data.appDate>=delivery.joinedDate }">
<td>{{$index+1}}</td>
<td>{{data.name }}</td>
<td>{{data.age}}</td>
<td>{{data.dept}}</td>
<td>{{data.appDate }}</td>
<td>{{data.joinedDate}}</td>
</tr>

Stylesheet:

.my-css-class {
background-color: #ffd6d6;
border: dashed 3px #9e0b0f;
}

applying conditionally css class on input element

If you are using Angular 2/ Angular 4 the below is the conditional syntax for NgClass

<some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element>

and if You are using angularJs(i.e. angular 1.x) use below

<some-element ng-class="{'fist' : true, 'second': true}">...</some-element>

Official Docs for Angular4 [NgClass]

Official DOcs for AngularJS ng-class

hope this helps :)

Conditional ng-style

You don't need to put the condition in the curly braces. And as for ng-style here, the way I understand it is you are replacing the border property of the styles that are being applied to this element.

Also if you are trying to change the border I don't think border: red or border:black are valid css statements. One way to solve this problem is writing it like this

<span ng-style="thumb.selected ? {'border-color': 'red'} : {}" 
style="border:1px solid black">Your text here </span>

You might wanna look into ng-style and css border property

AngularJS ng-style with a conditional expression

As @Yoshi said, from angular 1.1.5 you can use-it without any change.

If you use angular < 1.1.5, you can use ng-class.

.largeWidth {
width: 100%;
}

.smallWidth {
width: 0%;
}

// [...]

ng-class="{largeWidth: myVar == 'ok', smallWidth: myVar != 'ok'}"

How to apply css class based on condition that char length 128

You can do it like this :

<input [ngClass]="{ 'class1': charlen < 128, 'class2': charlen >= 128 }" />

What is the best way to conditionally apply a class?

If you don't want to put CSS class names into Controller like I do, here is an old trick that I use since pre-v1 days. We can write an expression that evaluates directly to a class name selected, no custom directives are necessary:

ng:class="{true:'selected', false:''}[$index==selectedIndex]"

Please note the old syntax with colon.

There is also a new better way of applying classes conditionally, like:

ng-class="{selected: $index==selectedIndex}"

Angular now supports expressions that return an object. Each property (name) of this object is now considered as a class name and is applied depending on its value.

However these ways are not functionally equal. Here is an example:

ng-class="{admin:'enabled', moderator:'disabled', '':'hidden'}[user.role]"

We could therefore reuse existing CSS classes by basically mapping a model property to a class name and at the same time keep CSS classes out of Controller code.

AngularJS - Conditionally apply style using ng-style to first element in ng-repeat

<div class="row" 
ng-style="{ true : rowCss }[$first]"
ng-repeat="top in gridObj">
...

Plunker

How to conditionally apply styles on the component tag based on the visibility of component contents?

Since there are no children, you can do this with a css selector:

.hello-class:not(:empty) {
display: block;
margin-bottom: 80px;
}

By using :not(:empty) it checks if the element (the host element for the component) has children. If it doesn't have children, then the style won't apply.

https://developer.mozilla.org/en-US/docs/Web/CSS/:empty

Conditional Styling of an Angular component

ng-style is the syntax for AngularJS. For Angular 2+, use [ngStyle]="" syntax. (see documentation)

<div class="col-md-3 d-flex justify-content-center align-items-center" 
[ngStyle]="{'background-color': (vars.state=='Signup') ? '#73c7af' : '#ffffff'}">


Related Topics



Leave a reply



Submit