Prevent mat-option selection if condition

给你一囗甜甜゛ 提交于 2020-01-06 02:40:48

问题


I want to prevent mat-option from being selected because clicking on it will open a dialog. Only when selecting something from the dialog, should my option be selected. If nothing was selected from the dialog, mat-option should not be changed from previous value.

<mat-select 
        [(ngModel)]="filter_defaultSelectedValue" 
        (change)="changeSelectedValue($event.value)">
   <mat-option *ngFor="let filter of filters" [value]="filter">
      <span *ngIf="filter.id != 'custom'; else content_dialog">
         {{filter.label | i18n}}
      </span>
      <ng-template #content_dialog>
         <dialog
            [filterParams] = "filter.value">
         </dialog>
      </ng-template>
   </mat-option>
</mat-select>

My mat-select has the following options: "yesterday", "today", "tomorrow", "custom range". For example when I click on "yesterday" it just gets selected, but when I click on "custom range" a dialog opens with a calendar. If I select a date from the calendar, dialog closes and the "custom range" option is selected as well. When I close the dialog without selecting anything from the calendar, "custom range" option gets selected again. I would not like this selection to happen since I didn't select anything from calendar. How can I condition this?

mat-options


回答1:


I've managed to condition this special case by changing in code the ngModel "filter_defaultSelectedValue". If inside the dialog nothing was selected, ngModel is set to some previously set value:

this.filter_defaultSelectedValue = this.lastSelection;

If something inside dialog was selected, then I let mat-select change my "filter_defaultSelectedValue" to that selected value.




回答2:


Thanks, this helped me. I had a very similar use case and I'm using reactive forms. In my app if a user selects a particular value from the mat-select a special warning popup is shown with Accept, Cancel buttons. If the user accepts, the particular value will stay set. But, if the user chooses to cancel, the previous value should be set. As the (valueChange) event on mat-select fires before the model [(ngModel)] is updated I was able to store the previous value in a component property called previousOption. I then databound another property called currentOption to the [(ngModel)] and with event binding (valueChanges) set the previous option to the current option. You can then hookup your (selectionChange) to do whathever.



来源:https://stackoverflow.com/questions/50156849/prevent-mat-option-selection-if-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!