8

I wonder when should use ngClass instead class I noticed that this style in css file

.someClass {
  color: red;
}

<div [ngClass]="['someClass']">Some text</div>
<div class="someClass">Some text2</div>

working properly for two div with diff aproach. I write that when we use condition is good practice using [ngClass]. Why else? What are the benefits using [ngClass] instead class ?

Walter White
  • 976
  • 4
  • 12
  • 29
  • 1
    This is incorrectly marked as a duplicate. The linked question is asking about `[class.someClass]`, this question is not. – derpedy-doo Jun 08 '22 at 19:45

2 Answers2

6

using ngClass we can use expressing for class, for example, if you want to use a condition based class then need to use ng-class

<button ng-class="row.bstatus?'btn red btn-outline':'btn green-haze btn-outline'">{{row.bstatus?'Deactivate':'Activate' }}</button>

RANVIR GORAI
  • 1,226
  • 11
  • 10
  • 1
    Hi Ranvir, I can do with help of angular expression as well then what is the benefit over here. like: `` – Akshay Pingle Mar 31 '19 at 04:19
  • @AkshayPingle I was wondering that too. Did you just make an observation that your syntax causes equivalent behavior or are you able to provide an explanation as to why *[class]* and *[ngClass]* are not merely copies of each other. Too me, it appears like a duplicate of already existing functionality but I'm convinced that there's a point to the latter, although I'm not realizing it. – Konrad Viltersten Jan 19 '20 at 08:12
5

Not much benefit using it to put the single literal class name. The benefit would be to use it to dynamically set the class.

Read more here.

ChiefTwoPencils
  • 13,548
  • 8
  • 49
  • 75
  • Since `ngClass` will contain a value which will be binded with its component, so perhaps, when the browser loads that component, the `ngClass` syntax will fetch the value from the component and do stuff accordingly. Whereas, in case of only `class` syntax, there will not be data-binding, so in case something breaks at the component's end, the class will not be rendered cleanly in the DOM. What do you think about this perspective? – Sahil Babbar Sep 06 '18 at 06:31
  • @SahilBabbar What if we use *[class]* instead of just *class*? Wouldn't that cause data-binding to occur? (I'm always using *ngClass* and data-bind it bracket'ly because that's the recommended approach in the official docs but lately, it hit me that I can't motivate nor explain *[class]* wouldn't have the same effect. It stroke me that *ngClass* appears to be a feature with no new purpose. And I'm sure as a hell that the Angular team won't waste time on unnecessary crap...) – Konrad Viltersten Jan 19 '20 at 08:08