0

I have a div with a class baz. If a condition is fulfilled, an additional class should be applied to it named qux. Right now I'm doing it so:

<div [class]="(bar == 'foo')?'baz':'baz qux'">

I'd like to know if there's a better solution, as this one can get quite redundant for elements having not only one (baz) but multiple default classes. In that case, all those default classes must be written twice in the code.

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
tom
  • 2,137
  • 2
  • 27
  • 51
  • 1
    you can use [ngClass] instead of class! – JayDeeEss Sep 21 '17 at 13:13
  • Im really curious as to why one would need to add multiple classes to an element in Angular 4. – Pytth Sep 21 '17 at 13:14
  • @Pytth I'm probably not completely getting the point of Angular yet. I've just started to use it. Could you suggest maybe some useful relevant resources so I can learn why a single class is sufficient? – tom Sep 21 '17 at 13:22
  • @tom Well, what is it you are trying to accomplish by adding a class? In Angular, most of the time adding a class is most useful for kicking off some visual change/animation. – Pytth Sep 21 '17 at 13:28
  • @Pytth It's a tab of a bootstrap navigation component. It has a default *nav-link* class, and if that's the tab currently open, I append an *active* class to it so bootstrap gives it the corresponding look. – tom Sep 21 '17 at 13:36
  • 1
    @tom If that's the case, a simpler approach would be for the element to start with all the classes it needs for the "look" you seek, along with an extra one that effectively resets the properties set by the other classes. When you want the element to have the "look," remove the "reset" class. – Pytth Sep 21 '17 at 15:00

0 Answers0