ng-class
and ng-style
both seem to be methods of dynamically setting CSS classes. What is the difference between them?

- 19,209
- 22
- 79
- 122
-
1[`ng-class`](https://docs.angularjs.org/api/ng/directive/ngClass) sets classes. [`ng-style`](https://docs.angularjs.org/api/ng/directive/ngStyle) sets styles. [This answer](http://stackoverflow.com/questions/13813254/how-do-i-conditionally-apply-css-styles-in-angularjs#13813255) might be informative. – showdev Nov 13 '14 at 22:55
4 Answers
ng-style is used to interpolate javascript object into style attribute, not css class.
Following directive will be translated to style="color:red"
ng-style="{color: 'red'}"
And ng-class directive translates your object into class attribute.
Following will be translated to class="deleted" when isDeleted variable is true.
ng-class="{'deleted': isDeleted}"
Note:
There is one more use case for ng-style. If you want to interpolate something in style attribute, you should consider using ng-style. Otherwise, that would not work before Internet Explorer 11 as documentation suggests.
So, instead of using style:
style="width: {{progress}}"
Use ng-style:
ng-style="{'width':progress}"

- 4,055
- 1
- 23
- 31
In ng-class
you are loading a CSS class defined in some place, like Bootstrap. In ng-style
you are setting the CSS style that you want that element has, example:
ng-style="{ 'background-color': person.email == selectedPerson.email ? 'lightgray' : ' '}" //background-color is a style
has-error
is a class defined in somewhere that is composed by style(s):
ng-class="{ 'has-error’: !theForm.email.$valid, 'has-success':theForm.email.$valid}

- 7,681
- 17
- 73
- 127

- 61
- 1
- 3
From the official Docs: https://angular.io/api/common/NgClass
These are different ways to use ngClass
...
<some-element [ngClass]="['first', 'second']">...</some-element> <some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-
element>
<some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element> <some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>
2. Similarly with ngStyle you can do the following:
**< some-element [ngStyle]="{'font-style': styleExp}">...</some-element>**
Your styleExp can be anything that evaluates to a legal value for the attribute you are setting ,e.g. font-size in the example above
Alternatively,
****< some-element [ngStyle]="objExp">...****
Where objExp is an object containing key-value pairs of your style attributes e.g. { width: 40, margin: '2em' } etc.

- 3,373
- 2
- 21
- 17
Theoretically they both are different, but practically at some point they both become same
ngStyle is used to add style dynamically at run time and
ngClass is used to add some class dynamically at run time but class also holds some css content, so indirectly you are also adding css here dynamically

- 1,840
- 1
- 18
- 16