简体   繁体   中英

pop element from array on selectionchange()

i am using angular. i have a multiple select (mat select) and i want to send the selected values in array i try to use selectionchange and get the value and push it in array but after that if i unselect an option that dosent pop from the array instead a value added in my array.i want if i unselect any element no new element inserted in that array

thanks in advance

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

You can use onSelectionChange event on mat-option like below

<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);
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM