I have class with some properties:
export class Task {
name: string;
state: number;
}
In my component.ts I have an array of objects with class Task (tasks).
In template I show them like this:
<div *ngFor='let task of tasks'>
<p>{{ task.name }}</p>
<p>{{ task.state }}</p>
</div>
Is it possible to change styling of my div based on task.state property? For example, I want it to be with red background when it's 0 and yellow when it's 1. I think I need to use directives, but I can't understand how.
Angular gives you two directives to style your element. You can use either
ngStyle
orngClass
for styling purpose.
In your scenario you can use -
-ngClass
Firstly create two css classes with name 'red-bg' and 'ylow-bg' according to their behaviour.
<div *ngFor='let task of tasks' [ngClass]="task.state === 0?'red-bg':'ylow-bg'">
<p>{{ task.name }}</p>
<p>{{ task.state }}</p>
</div>
-ngStyle
<div *ngFor='let task of tasks' [ngStyle]="{'background-color':task.state===0?'red':'yellow'}">
<p>{{ task.name }}</p>
<p>{{ task.state }}</p>
</div>