簡體   English   中英

在循環中為布爾變量分配一個值* ngFor

[英]Assign a value to a boolean variable in loop * ngFor

我的組件window-container中有一個ngFor循環,其中有幾個顯示的聊天窗口( window-item )。 我想將一個變量( changeColor )設置為true,將兩個div設置為false,將另一個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>

我希望每個div的變量changeColor更改值,以便將其寫入我的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;
      }
   }
}

您可以像這樣使用它:

建議您通過ngFor odd / even ngFor

even :boolean:當項目在可迭代對象中具有偶數索引時為true。

奇數 :布爾值:當項目在可迭代項中具有奇數索引時為true。

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

工作演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM