Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between ng-class and ng-style?

Tags:

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

like image 786
David says Reinstate Monica Avatar asked Nov 13 '14 22:11

David says Reinstate Monica


People also ask

Do we need Ng-class or ng-style directives in Angular 2?

Out of the box with the new syntax we don't need special ng-class or ng-style directives like in Angular 1. But with Angular we still have these built in directives. These directives offer syntactic sugar for more complex ways of altering our element styles. First lets look at ngStyle.

What is the difference between ngstyle and style?

With ngStyle, you can bind to an object that expresses as many conditions and cases as you need: Now you can express as many different styles as needed. ngStyle is an Angular directive that gives you the flexibility to do this, where as style is a regular HTML property to which you can only bind values one by one.

What is the difference between ngclass and ngclass?

Theoretically they both are different, but practically at some point they both become same 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

Should I use ngclass or CSS pseudo classes for state styles?

Note that many state styles can be natively implemented using browser CSS pseudo-classes, such as for example: For these type of state styles natively supported by the browser, it's better to use the CSS pseudo classes whenever possible. So for these very common cases we won't need ngClass.


1 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}" 
like image 121
halilb Avatar answered Oct 04 '22 09:10

halilb