user9099802
user9099802

Reputation: 253

Change the style of one element of two with a *ngFor

I realize an instant messenger. The user can display two chat windows at the same time. I want the first window displayed to be in blue and the second to be gray.

Here is what I have:

<div class="chat-window-container" style="z-index: 1040">
  <window-item
    *ngFor="let thread of (windows ? windows.slice(0,2):[])"
    [thread]="thread">
  </window-item>
</div>

I want that one window-item on two is blue, an dthe other is grey.

//////UPDATE//////

Here is my window-container.html :

<div class="chat-window-container" style="z-index: 1040">
  <window-item
    *ngFor="let thread of windows; let i = index"
    [class.myColorClass1]="i % 2 == 0" [class.myColorClass2]="i % 2 != 0"
    [thread]="thread">
  </window-item>
</div>

Here is my window-container.scss:

.myColorClass1 {
  color: blue;
}
.myColorClass2 {
  color: grey;
}

It works well on every other window, but I have another problem. My window-container file does not change the good part of my div. The div I want to edit is in another component: window-item.

<div class="panel-heading top-bar">

Can I change the style of a div of the window-item component in the .scss filer of the window-container component?

Upvotes: 0

Views: 2231

Answers (1)

alsami
alsami

Reputation: 9845

Use index and do a simple modulo.

<window-item *ngFor="let thread of windows; let i = index" [class.myColorClass1]="i % 2 === 0" [class.myColorClass2]="i % 2 !== 0"> 
</window-item>

Edit:

If you want the childs div (window-item, div inside) to change it's color, pass the index as input to the component.

@Input() index: number;

Then do the modulo thing in your childs template as you would have used it for the childs-selector (window-item).

Edit 2018-11-14:

Instead of using the index and doing modulo within the template, you can let odd or even the same way you would index. I created a stackblitz sample here.

Upvotes: 2

Related Questions