【问题标题】:pop element from array on selectionchange()在 selectionchange() 上从数组中弹出元素
【发布时间】:2021-01-29 19:05:46
【问题描述】:

我正在使用角度。我有一个多重选择(垫选择),我想在数组中发送选定的值我尝试使用 selectionchange 并获取值并将其推送到数组中,但之后如果我取消选择从数组中弹出的选项而不是一个值添加到我的数组中。我想如果我取消选择任何元素,则该数组中没有插入新元素

提前致谢

<mat-form-field>
  <mat-select  (selectionChange)="change($event)" multiple >
    <mat-option *ngFor="let i of user" [value]="i">
      {{ i.name }}
    </mat-option>
  </mat-select>
</mat-form-field>


  change(event) {
    console.log(event);
    this.e=event.value
    console.log('ttttt',this.e)
    for(var i=0;i<this.e.length;i++)
    {
      var local=this.e[i].value;
    }
  this.arr.push(local);
  console.log('arr',this.arr)
  }

【问题讨论】:

    标签: javascript arrays angular


    【解决方案1】:

    您可以在 mat-option 上使用 onSelectionChange 事件,如下所示

    <mat-form-field>
        <mat-select multiple>
                <mat-option (onSelectionChange)="change($event)" *ngFor="let i of user" [value]="i">
                    {{ i.name }}
        </mat-option>
    </mat-select>
    
      change(event) {
        if (event.source.selected) this.arr.push(event.source.value);
        else {
          const index = this.arr.indexOf(event.source.value);
          if (index > -1) {
            this.arr.splice(index, 1);
          }
        }
        console.log("arr", this.arr);
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-20
      • 2011-06-22
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-14
      相关资源
      最近更新 更多