Geoffrey Geoffrey - 1 month ago 19
TypeScript Question

ng-class not working on

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

Answer

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.

Comments