【问题标题】:Change the style of one element of two with a *ngFor使用 *ngFor 更改两个元素中的一个元素的样式
【发布时间】:2018-08-06 03:13:19
【问题描述】:

我意识到一个即时通讯工具。用户可以同时显示两个聊天窗口。我希望第一个窗口显示为蓝色,第二个显示为灰色。

这是我所拥有的:

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

它适用于所有其他窗口,但我还有另一个问题。我的窗口容器文件不会改变我的 div 的好部分。我要编辑的 div 在另一个组件中:window-item。

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

可以在window-container组件的.scss filer中更改window-item组件的div的样式吗?

【问题讨论】:

    标签: html css angular ngfor


    【解决方案1】:

    使用索引并做一个简单的模数。

    <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 inside)改变它的颜色,请将索引作为输入传递给组件。

    @Input() index: number;
    

    然后在您的孩子模板中做模运算,就像您将它用于孩子选择器(窗口项目)一样。

    2018-11-14 编辑:

    除了在模板中使用索引和取模,您可以让奇数甚至与索引相同的方式。我创建了一个 stackblitz 示例 here

    【讨论】:

    • 非常感谢,它运行良好,但我还有另一个问题。我更新了我的帖子
    • 抱歉,我不明白我在 window-container.component.ts 中添加了@Input() index: number;。但是我不知道模板之后该怎么做...
    猜你喜欢
    • 2017-07-16
    • 1970-01-01
    • 2011-10-21
    • 2016-06-03
    • 1970-01-01
    • 1970-01-01
    • 2019-01-21
    • 2012-09-07
    • 2022-01-04
    相关资源
    最近更新 更多