1

I can't make Angular2 work with a conditional ngClass styling and bootstrap labels.

<h1 [ngClass]="{'label label-warning': yourName=='Daniel', 
                'label label-success': yourName!='Daniel'}">

ngClass appears to be removing the first 'label' from a 'label label-success' when I style my app. It correctly styles when the second conditional is met, but when the first conditional is met, the styling is incorrect.

On inspection of the element, when the second conditional has been met the style is h1.label.label-success, however when the first condition is met it is incorrectly styled as h1.label-error.

See this plunker for the error.

https://plnkr.co/edit/qJLWBzCXXUn7hNKEWXIs?p=preview

I have followed the AngularJS Upgrade guide (https://angular.io/docs/ts/latest/cookbook/a1-a2-quick-reference.html) but cannot get it to work correctly

dannash918
  • 434
  • 6
  • 14
  • checkout solution here http://stackoverflow.com/questions/42017246/angular2-toggle-icons-inside-ngfor/42017945#42017945 it might help – angularrocks.com Feb 06 '17 at 09:21
  • See the above question, I had the same issue. By having the same style you're telling angular to add label when one value is true, and remove that value when it is false. Add label using the traditional tag `class="label"` – Christopher Moore Feb 06 '17 at 09:57

2 Answers2

12

I think in [ngClass] you can pass a single class name in a single object key. So put your fixed common class directly in a html class using simply class="label" and add a conditionally class only inside [ngClass]

<h1
    class="label"
    [ngClass]="{'label-warning': yourName=='Daniel','label-success': yourName!='Daniel'}">

Also, you can use angular 2 style class [class.classname]="condtionexpression"

<h1
    class="label"
    [class.label-warning]="yourName=='Daniel'"
    [class.label-success]="yourName!='Daniel'">
ABabin
  • 2,724
  • 24
  • 30
Kishan Mundha
  • 2,989
  • 18
  • 26
2

You could conditionally add the required label class (e.g. label-success) like this:

<h1 *ngIf="yourName" class="label" 
[class.label-warning]="yourName != 'Daniel'"
[class.label-success]="yourName=='Daniel'">
    Hello {{yourName}}!
</h1>

So it has a label class by default, then you append the additional class depending on your condition.

Garth Mason
  • 7,611
  • 3
  • 30
  • 39