0

Quick question. I am trying to deal with ng-class for the first time and I am wondering what I am doing wrong.

So in my HTML I have:

<ion-icon name="logo-facebook" class="big" ng-class="{selected: facebook.selected}" (tap)="addSocial('Facebook')" ></ion-icon>
<ion-icon name="logo-twitter" class="big" ng-class="{selected: twitter.selected}"  (tap)="addSocial('Twitter')"></ion-icon>

In my css I have:

page-social {

  .big{
    font-size:300%;
    display: inline-block;
    margin:2%;
  }

  .selected{
    font-size:300%;
    color:#9991ff;
  }
}

In my ts I have:

facebook = {
"selected" : false,
"type" : "Facebook"
}

twitter = {
"selected" : false,
"type" : "Twitter"
}
...
... 
    addSocial(type){
    // reinit all to selected false
    for(var i in this.all){
      this.all[i].selected = false;
    }
    switch(type) {
      case "Facebook":
      this.facebook.selected = true;
      break;
      case "Twitter":
      this.twitter.selected = true;
      break;
      case "Instagram":
      this.insta.selected = true;
      break;
      case "LinkedIn":
      this.linkedin.selected = true;
      break;
      case "Github":
      this.github.selected = true;
      break;
    }
    this.atLeastOneSelected = true;
    this.currentSocial = type;
    console.log(JSON.stringify(this.all));
  }

When I click on facebook I can see the text field appearing with "Entrez votre Facebook" and in my log I have:

[{"selected":true,"type":"Facebook"},{"selected":false,"type":"Twitter"},{"selected":false,"type":"Instagram"},{"selected":false,"type":"LinkedIn"},{"selected":false,"type":"Github"}]

Same thing for twitter [{"selected":false,"type":"Facebook"},{"selected":true,"type":"Twitter"},{"selected":false,"type":"Instagram"},{"selected":false,"type":"LinkedIn"},{"selected":false,"type":"Github"}]

When I apply the class 'selected' to the class directly it is working but with ng class it is not. What I am doing wrong?

I followed the topic here ng-class not being applied but not working for me with the '' in the class

Geoffrey
  • 1,151
  • 3
  • 13
  • 26
  • Please use the correct tag for the version of Angular you are using. `angularjs` is for AngularJS 1.x; `angular2` is for Angular 2. – Heretic Monkey Nov 04 '16 at 17:52

1 Answers1

2

Assuming you are using a recent Angular2 version (you mention typescript and ionic2) your binding needs to be [ngClass]=..., not ng-class=...

So you have the wrong property name as well as the missing brackets for the binding.

See here for documentation/examples: https://angular.io/docs/ts/latest/api/common/index/NgClass-directive.html

According to that you might also need quotes around the CSS class names, although I'm not sure whether they are really required.

Matthias247
  • 9,836
  • 1
  • 20
  • 29