Reputation: 161
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?
Upvotes: 0
Views: 333
Reputation: 479
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>
Upvotes: 0
Reputation: 17973
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.
Upvotes: 2
Reputation: 10263
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:
ngStyle
ngStyle
is a key:value hash, where the key
s are CSS property names, and the value
s 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
. Upvotes: 3