DEV Community

Cover image for Improving NgClass expression
Dimas López
Dimas López

Posted on

Improving NgClass expression

Sometimes happens that when you are working with a framework, you miss some features of the other. For me, this is something common because I work in Angular, Vue and (P)React (maybe others) almost every day and, when I work in Angular, I miss Vue, when I work in Vue I miss React and bla bla bla.

Today, let's talk about one difference between Vue and Angular in the class expression possibilities. Maybe, you should have some experience with Vue and Angular to get the point of this article.

For example, in Angular, you can use the following [ngClass] expressions:

Note: Let's omit [ngClass]="stringExp|arrayExp|objExp"

<!-- example of ngClass in Angular -->
<some-element [ngClass]="'first second'">...</some-element>

<some-element [ngClass]="['first', 'second']">...</some-element>

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

<some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>
Enter fullscreen mode Exit fullscreen mode

As you can see, the options is to use any expression as Array, Object or String where the first result, at the first level (first child) should return a string but, if you want to mix both or use a deeper child item, maybe you will have an error.

<!-- with ngClass of Angular -->
<some-element [ngClass]="[{'classA': true}, 'classB']">
  ...
</some-element>
<!-- ERROR Error: NgClass can only toggle CSS classes expressed as strings, got [object Object] -->
Enter fullscreen mode Exit fullscreen mode

As you can see, the example above, is a mix: An Array with an Object and String as item values.

If you have been working in Vue, you know that you can use more flexible expressions, so, the the example in Angular, we can do in Vue as in the following example:

<!-- with :class of Vue -->
<some-element :class="[{'classA': true}, 'classB']">
  ...
</some-element>
Enter fullscreen mode Exit fullscreen mode

For that, in my last applications, I made a directive to solve it and, the example is something like this:

<!-- with ngVClass of Angular -->
<some-element [ngVClass]="[{'classA': true}, 'classB']">
  ...
</some-element>
Enter fullscreen mode Exit fullscreen mode

The example above works. This is a directive that allows you to work with classes in Angular as in Vue.

Then I decided to share to the community publishing in a npm package https://ng-v-class.dimaslz.dev.

As always, I hope could be helpful, at least as learning. Feedback are welcome, support the library clicking in the star in the repo, always helps.

Thanks for reading.

Top comments (0)