0

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.

4
  • You can just use [ngClass] Commented Aug 1, 2020 at 12:41
  • @MikeOne And what should I write inside it? Commented Aug 1, 2020 at 12:45
  • 1
    stackoverflow.com/questions/35269179/… Commented Aug 1, 2020 at 12:49
  • 1
    [ngClass] = “{‘redClass’: task.state === 0, ‘yellowClass’: task.state === 1}” Commented Aug 1, 2020 at 12:50

1 Answer 1

1

Angular gives you two directives to style your element. You can use either ngStyle or ngClass 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>
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.