【问题标题】:Pop an item if its value is false如果项目的值为 false,则弹出项目
【发布时间】:2019-09-06 14:36:36
【问题描述】:

我正在使用来自 Angular Material 的多重选择。我能够获取项目的值和检查值(真/假)。我需要创建一个数组,如果该项为真则推送,如果该项为假则弹出。

我已经尝试获取布尔值:

html:

<mat-form-field>
     <mat-select multiple placeholder="Select Shows">
          <mat-option (onSelectionChange)="change($event)" *ngFor="let food of foods" [value]="food.value">
                    {{ food.viewValue }}
          </mat-option>
     </mat-select>
</mat-form-field>

.ts:

 change(event)
  {
    if(event.isUserInput) {
      console.log(event.source.value, event.source.selected);
      this.ShowArray.push(event.source.value)
    }
  }

预期输出:

["value1","value2","value3"]; //Inserted at first
["value1","value3"]; //Since the value2 is checked again, so it becomes false.

【问题讨论】:

  • event.source.selected 是布尔值吗?
  • 是的。它是布尔值

标签: angular angular-material


【解决方案1】:

第一次将事件绑定从选项更改为mat-select,例如:

<mat-form-field>
     <mat-select multiple placeholder="Select Shows" (selectionChange)="change($event)">
          <mat-option  *ngFor="let food of foods" [value]="food.value">
                    {{ food.viewValue }}
          </mat-option>
     </mat-select>
</mat-form-field>

现在更改您的更改方法,如下所示:

change(event)
{
      console.log(event.source.value, event.source.selected);
      this.ShowArray = event.source.value;
}

每次更改选择时,它都会发送 array 的项目,因此您可以直接使用该数组而无需任何额外的逻辑。

工作示例here

【讨论】:

  • @KedarKulkarni 不客气,如果这解决了您的问题,您可以考虑将此答案标记为已接受。
【解决方案2】:

每当有新的输入出现时,用

检查它
 change(event)
      { 
         flag = 0
        if(event.isUserInput) {

          console.log(event.source.value, event.source.selected);
           if(event.source.selected){
               if(!this.ShowArray.includes(event.source.value)){
                this.ShowArray.push(event.source.value)     
           }
           }else{
              this.ShowArray.splice(this.ShowArray.indexOf(eventevent.source.value) , 1);
           }


        }
      }

【讨论】:

  • this 的输出:["value1","value2","value3"] // 从下拉列表中选择。再次选择 value2 后,它应该从数组中弹出,但它仍然存在。 o/p: ["value1","value2","value3"]
  • @Pushprajsinh 通过从另一个人那里复制来编辑你的答案不是一个好习惯:)
  • @AdritaSharma ,也许我们的语法不同 :) 而且方式也不同。
  • 思路是一样的。
  • 世界上有60亿人口,任何人都可以有任何想法。巧合的是我们的想法是一样的。女士 :) @AdritaSharma
猜你喜欢
  • 2020-12-23
  • 1970-01-01
  • 1970-01-01
  • 2014-08-09
  • 1970-01-01
  • 2018-09-11
  • 2012-03-25
  • 2018-08-20
  • 1970-01-01
相关资源
最近更新 更多