Wenqi Xu
Wenqi Xu

Reputation: 63

How to cancel selectionChange event in angular material 2?

What i want is: if p1 or p2 is locked,the selected option remains unchanged; But the code below works incorrect.The selected option still changed. Can anybody gives me some advice?

html

<mat-form-field style="text-align: center; width: 25%;">
      <mat-select #singleSwap [(value)]="categoryProduct.sort"  
     (selectionChange)="singleSwapSelectionChange(singleSwap.value,categoryProduct.id)">
         <mat-option *ngFor="let option of options" [value]="option">
              {{ option }}
         </mat-option>
       </mat-select>
    </mat-form-field>

component

singleSwapSelectionChange(currentSelection: number, id: number) {
    let p1 = this.categoryProducts.find(p => p.sort === currentSelection);
    let p2 = this.categoryProducts.find(p => p.id === id);
    if (p1.is_locked || p2.is_locked) {
      console.log('locked!')
      return;
    }
    p1.sort = p2.sort;
    p2.sort = currentSelection;

Upvotes: 3

Views: 3967

Answers (2)

Luis Reales
Luis Reales

Reputation: 455

In the html send the event:

(selectionChange)="asignarProcedure_reasing($event,$event.value,value.id)"

Is necessary to receive the event in the method of ts:

asignarProcedure_reasing(e,user_id,procedure_id){

  if(result.dismiss){

            debugger;
            e.source.writeValue(0);

            // window.location.reload();
            // this.ngOnInit();           
         }

This worked for me. I hope it will work for you too.

Upvotes: 5

Florin D
Florin D

Reputation: 1870

The way I did this is

  1. One way binding in HTML
<mat-select [ngModel]="someProperty"
            (selectionChange)="changeSelect($event)" ....>
  1. Change handler
changeSelect( changeEvent: MatSelectChange): void {
  ..... OK to change
  this.someProperty = changeEvent.value;
  ..... else
  changeEvent.source.writeValue(this.someProperty);
  .....
}

Upvotes: 1

Related Questions