0
votes

In the following Ionic2/Angular2 template:

<ion-row style="background-color: #f4b434">
    <ion-col col-4><b>Brand</b></ion-col>
    <ion-col col-1><b>Qty</b></ion-col>
    <ion-col col-2><b>Sales</b></ion-col>
    <ion-col col-2 style="color: whitesmoke "><b>Qty</b></ion-col>
    <ion-col col-3 style="color: whitesmoke "><b>Sales</b></ion-col>
</ion-row>
<div *ngFor="let x of datasales">
    <ion-row>
        <ion-col col-4><b>{{x.Brand}}</b></ion-col>
        <ion-col col-1>{{x.Qty_Today | number:0 }}</ion-col>
        <ion-col col-2>{{x.SalesToday | number:0 }}</ion-col>
        <ion-col col-2>{{x.Qty_MTD | number:0 }}</ion-col>
        <ion-col col-3>{{x.Sales_MTD | number:0 }}</ion-col> 
    </ion-row> 
</div>

If x.Brand = 'Good' then in the second ion-row I want to add style="background- color:red".

How can I accomplish it?

3

3 Answers

3
votes

You may use ngStyle as per Angular 2 docs, eg. like this:

<div *ngFor="let x of datasales"> 
  <ion-row [ngStyle]="{'background-color' : x.Brand==='Good'? 'red' : ''}">
    <ion-col col-4><b>{{x.Brand}}</b></ion-col>
    ...
  </ion-row> 
</div>

Please note:

  1. don't forget the square brackets around ngStyle
  2. the value of ngStyle is a key:value hash, where the keys are CSS property names, and the values are expressions. In the above case, I used a test on x.Brand to decide which value should be assigned to the background-color property of the div.
2
votes

Similar to Paolos answer, when only affecting one property, you can use the [style.prop]="expr" syntax, where prop is the css property you want to affect, and expr is the expression you want to evaluate.

<ion-row [style.background-color]="x.Brand==='Good'?'red':''">
</ion-row>

This also works similar with ngClass, as you can use [class.className]="expr" to apply .className if expr is true. As such you can add a class to your styles

.is-good-brand {
  background-color: red;
}

and in your template use

<ion-row [class.is-good-brand]="x.Brand==='Good'">
</ion-row>

Since you only want to apply a style if the condition is fulfilled.

0
votes

You can use ngStyle like this;

<ion-row style="background-color: #f4b434">
    <ion-col col-4><b>Brand</b></ion-col>
    <ion-col col-1><b>Qty</b></ion-col>
    <ion-col col-2><b>Sales</b></ion-col>
    <ion-col col-2 style="color: whitesmoke "><b>Qty</b></ion-col>
    <ion-col col-3 style="color: whitesmoke "><b>Sales</b></ion-col>
</ion-row>
<div *ngFor="let x of datasales"
    [ngStyle]="{backgroundcolor: x.brand='Good' ? 'red' : 'transparent'}">
    <ion-row>
        <ion-col col-4><b>{{x.Brand}}</b></ion-col>
        <ion-col col-1>{{x.Qty_Today | number:0 }}</ion-col>
        <ion-col col-2>{{x.SalesToday | number:0 }}</ion-col>
        <ion-col col-2>{{x.Qty_MTD | number:0 }}</ion-col>
        <ion-col col-3>{{x.Sales_MTD | number:0 }}</ion-col> 
    </ion-row> 
</div>