Ion tabs -- change color from json response


#1

I am using Ionic v2 to develop hybrid app.

Requirement : Change ion tabs text and icon color dynamically from json response.

Analysis so far : This can be achieved with pre-defined sass variable(s) color and applying it at template.

Issue: How to get the colors added from json variable ?

I searched a lot but not finding exact answer to my question.

As an alternative, we can go with grids, but again there will be lot of CSS required to get Tabs UI. Not recommended.

Appreciate the support here !


#2

you can add classes to your tabs that cange their colorwith ngClass or ngStyle.

My solution ideas:

  • if you have a defined color set you can have all those colors as classes in your scss and apply them with ngClass. (Important: use http://sass-lang.com/guide ->Nesting)
  • if you have to dynamicaly get any color you can also change your colors with ngClass, but you have to create those nested css classes at runtime.
  • I don’t know if you could get ngStyle to work properly, because I think you can’t get the right elements to dye because they are probably not generated before runtime.

#3

Thanks for the reply.

Point 1 – Agreed.

Point 2 – If we inspect DOM generated post adding ion tabs – text color are added to inner elements. Accessing this at run time will be difficult and I think its not recommended too.

Point 3 – Yes.

Grid with same methodolgy.
Because I am able to achieve all the requirements but it involves more custom logic.

ion-tabs is good component and need to use same.


#4

css also has nesting its just other syntax : https://www.w3schools.com/css/css_combinators.asp (look for Child Selector) => its not more dificult as generating classes at runtime.

or you could theoreticaly write a new (typescript) tab class that extends the ionic tab class for that purpose.


#5

Hummm if you create in variable.css others colors that can be setted by the name string and then you create a model in ts wich changes depending of the json response?

<ion-tabs selectedIndex="0" color="{{color}}">
  <ion-tab [root]="tab1Root" tabTitle="Acces" tabIcon="person"></ion-tab>
  <ion-tab [root]="tab2Root" tabTitle="Register" tabIcon="create"></ion-tab>
  <ion-tab [root]="tab3Root" tabTitle="guess" tabIcon="walk"></ion-tab>
</ion-tabs>

and then in .ts

color: string =='';


ionViewDidLoad{

if(json == 'somedata'){
this.color = 'danger'
}

in variable.css

$colors: (
  primary:    #488aff,
  secondary:  #32db64,
  danger:     #f53d3d,
);

Maybe something like this could be work