使用 *ngFor 更改两个元素中一个元素的样式

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

我实现了一个即时通讯工具。用户可以同时显示两个聊天windows。我希望第一个 window 显示为蓝色,第二个显示为灰色。

这是我的:

<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>

我想要一个 window-item on two 是蓝色的,另一个是灰色的。

//////更新//////

这是我的 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>

这是我的 window-container.scss:

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

它在其他 window 上运行良好,但我有另一个问题。我的 window-container 文件没有改变我的 div 的好的部分。我要编辑的 div 在另一个组件中:window-item.

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

我可以在 window-container 组件的 .scss 文件管理器中更改 div 的 window-item 组件的样式吗?

使用索引并进行简单的取模。

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

编辑:

如果您希望子项 div(window-item、div 内部)更改其颜色,请将索引作为输入传递给组件。

@Input() index: number;

然后在您的孩子模板中执行取模操作,就像您将它用于 childs-selector (window-item) 一样。

编辑 2018-11-14:

除了在模板中使用索引和取模之外,您还可以使用与索引相同的方式使用奇数或偶数。我创建了一个 stackblitz 示例 here.