3

I'm playing around with ngClass, and I do not know what I am doing wrong. It is showing weird behavior. It seems like when I assign a function to ngClass it does not work, but if I assign it an object literal it works. How can I get ngClass to work with my Component's function?

ProposalForm.ts

import {Component} from 'angular2/core';
import {NgClass}    from 'angular2/common';
@Component({
  selector: 'proposal-form',
  template: `
   <div [ngClass]="setClasses()">
    ghtfhg
  </div>
  <div [ngClass]="{active:true, disabled:true}">
    1111111
  </div>`,
  directives:[NgClass]
})
export class ProposalForm {

  setClasses() {
   return {active:true, disabled:true};
  }
}

Looking at Chrome's Inspector this is the HTML

<proposal-form _ngcontent-xxb-2="">
<div class="">
  ghtfhg
</div>
<div class="active disabled">
  1111111
</div></proposal-form>
WShell
  • 58
  • 1
  • 7

2 Answers2

2

@WShell. You are doing everything correctly. However, I have reported this issue to the angular team and they have confirmed that this is a bug. Setting the Classes like you have from the component with the method setClasses does not work in the last few builds of Angular2. For now you must set your classes dynamically inline like this:

[ngClass]="{active: isOn, disabled: isDisabled}"

Like to reported issue: https://github.com/angular/angular/issues/7426

Nige
  • 1,206
  • 2
  • 10
  • 21
1

You don't provide much information about what or how it's not working. I assume the problem is that setClasses() always returns a different object and Angulars change detection doesn't like that.

You should instead bind to a field

classes = {active:true, disabled:true};

and then update the value of classes when a value it depends on changes.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Thank you, that solved it. But, why didn't binding ngClass to a function work? In that simple example, the object does not change. So I was assuming when Angular loads the component and call's the function, it is similar to just reading the object from the component's property. – WShell Mar 09 '16 at 17:52
  • 1
    Yes it changes. Every time Angular change detection runs it evaluates the binding expression `setClasses()` and every time it gets a new object instance. It doesn't matter to Angular that the content is the same. It's a new object and when it compares the identity of the previously and currently returned value, they are not equal. – Günter Zöchbauer Mar 09 '16 at 17:59