【问题标题】:Disabling an element in Array depending on condition in angular 5根据角度 5 中的条件禁用 Array 中的元素
【发布时间】:2018-05-27 13:16:56
【问题描述】:

我有一份参与者名单:

<div class="heroWrapper">
    <div class="image hero" *ngFor="let participant of participants; index as i" [class]="i === selectedParticipant ? 'selected hero' : 'image hero'">
        <img [src]="participant.imageUrl" (click)="toggleMoves = !toggleMoves"/>
        <span [ngStyle]="{'color': getColor(participant)}" class="HP">{{participant.hitPoints}}</span>
        <span class="namePlayer" *ngIf="isHero(participant)">{{getPlayerName(participant)}}</span>
        <span class="nameHero">{{participant.name}}</span>
    </div>
</div>

还有一个下一个和上一个按钮:

next() {
    if (this.selectedParticipant != this.participants.length - 1) {
        ++this.selectedParticipant;
    } else {
        this.selectedParticipant = 0;
    }

    this.toggleMove();
}

previous() {
    if (this.selectedParticipant != 0) {
        --this.selectedParticipant;
    } else {
        this.selectedParticipant = this.participants.length - 1;
    }

    this.toggleMove();
}

selectedParticipant 是数组中元素的索引。 现在,当参与者HP为0时,我希望他们被禁用,这意味着他们将被下一个和上一个方法跳过。当它们被禁用时,我希望它们变灰。

我尝试添加

if (this.participants[selectedParticipant].hitPoints = 0) {
    ++selectedParticipant;
    if (this.selectedParticipant != this.participants.length - 1) {
        ++this.selectedParticipant;
    } else {
        this.selectedParticipant = 0;
    }
}

我必须使用相同的代码两次,因为每个团队都必须检查它。但由于某种原因,这将参与者的 hitPoints 设置为 0?

【问题讨论】:

    标签: angular typescript components


    【解决方案1】:

    你的 if 语句需要有 == 而不是单个 =,这就是为什么参与者的 hp 设置为 0

    == 是比较运算符

    = 是赋值运算符

    next() {
        if(this.participants[selectedParticipant].hitPoints == 0) {
           ++this.selectedParticipant;
           if (this.selectedParticipant > this.participants.length - 1) {
               this.selectedParticipant = 0;
           }
    
           this.toggleMove();
        }
    }
    

    【讨论】:

      【解决方案2】:

      这里是赋值而不是比较。

      养成在左侧写常量的习惯,这样就不会发生赋值而不是比较。

      例如。

      if (0 == this.participants[selectedParticipant].hitPoints) { 
      }
      
      
      
      if (0 = this.participants[selectedParticipant].hitPoints) {
      } // it would break the execution and give an error because constants cant be assigned a value and so you find out the error easily.
      

      【讨论】:

        猜你喜欢
        • 2018-04-23
        • 1970-01-01
        • 2019-01-17
        • 2018-07-10
        • 2016-08-26
        • 2018-10-11
        • 1970-01-01
        • 2019-02-03
        • 2011-03-30
        相关资源
        最近更新 更多