【问题标题】:Assign a value to a boolean variable in loop * ngFor在循环 * ngFor 中为布尔变量赋值
【发布时间】:2018-08-06 20:46:38
【问题描述】:

我的组件 window-container 中有一个 ngFor 循环,其中显示了几个聊天窗口 (window-item)。我想为两个上的一个 div 设置一个变量 (changeColor) 为 true,为两个上的另一个 div 设置为 false。 我希望能够在两个组件中使用这个变量:window-containerwindow-item

这是我在window-container.html 中所做的,但它不起作用:

<window-item
  *ngFor="let thread of windows; let i = index"
    [thread]="thread">
      <div *ngIf="i % 2 == 0"> {{this.threadService.changeColor = false}}</div>
      <div *ngIf="i % 2 != 0"> {{this.threadService.changeColor = true}}
    </div>
</window-item>

我希望变量 changeColor 更改每个 div 的值,以便将其写在我的 window-item.html 中:

<div [ngClass]="{'window-grey' : !this.threadService.changeColor, 'window-blue': this.threadService.changeColor}">
    <div class="panel-container">
      <div class="panel panel-default">
        ...
      </div>
    </div>
</div>

还有我的window-item.scss

.panel-heading {
   .top-bar {
      .window-grey {
         background: grey;
      }
      .window-grey {
         background: grey;
      }
   }
}

【问题讨论】:

    标签: html angular ngfor angular-ng-if


    【解决方案1】:

    你可以像这样使用它:

    建议您通过odd / evenngFor 传递它

    even: boolean: 当项目在可迭代对象中有偶数索引时为真。

    奇数:布尔值:当项目在可迭代对象中有奇数索引时为真。

    <window-item
      *ngFor="let thread of windows; let i = index ; let odd = odd;"
        [thread]="{ thread : thread , changeColor : odd }">
          <!-- <div *ngIf="i % 2 == 0"> {{this.threadService.changeColor = false}} </div>
          <div *ngIf="i % 2 != 0"> {{this.threadService.changeColor = true}} </div> -->
    </window-item>
    
    // window-item.html
    <div [ngClass]="{'window-grey' : !changeColor, 'window-blue': changeColor}">
        <div class="panel-container">
          <div class="panel panel-default">
            ...
          </div>
        </div>
    </div>
    

    WORKING DEMO

    【讨论】:

    • 感谢您的回答,但它不起作用。我没有可以打开的窗口
    • 如何创建一个@input "odd"
    • @Eliseo 我在哪里写 @input "odd ?在window-container.component.ts ?
    • @user9099802 是的
    • 我认为您的窗口项是“窗口容器”的“子项”。我认为您正在使用 @input 传递 [thread] :(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-10
    • 2011-02-28
    相关资源
    最近更新 更多