如果有条件,防止垫选项选择

Prevent mat-option selection if condition

我想阻止 selected mat-option,因为点击它会打开一个对话框。只有当 select 从对话框中输入某些内容时,我的选项才应该 selected。如果没有从对话框中 select 编辑任何内容,则垫选项不应从以前的值更改。

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

我的垫子-select有以下选项:"yesterday"、"today"、"tomorrow"、"custom range"。例如,当我单击 "yesterday" 时,它只会得到 selected,但是当我单击 "custom range" 时,会打开一个带有日历的对话框。如果我 select 日历中的日期,对话框将关闭并且 "custom range" 选项也会被 select 编辑。当我在没有从日历中 selecting 任何内容的情况下关闭对话框时,"custom range" 选项再次得到 selected。我不希望这种 selection 发生,因为我没有 select 日历中的任何内容。我该如何调节?

mat-options

我已经通过更改代码中的 ngModel "filter_defaultSelectedValue" 设法解决了这个特殊情况。 如果对话框内没有任何内容 selected,ngModel 将设置为某个先前设置的值:

this.filter_defaultSelectedValue = this.lastSelection;

如果对话框中的某些内容被 selected,那么我让 mat-select 将我的 "filter_defaultSelectedValue" 更改为那个 selected 值。

谢谢,这对我有帮助。我有一个非常相似的用例,我正在使用反应形式。在我的应用程序中,如果用户 select 从 mat-select 中获取特定值,则会显示带有接受、取消按钮的特殊警告弹出窗口。如果用户接受,特定值将保持不变。但是,如果用户选择取消,则应设置以前的值。由于 mat-select 上的 (valueChange) 事件在模型 [(ngModel)] 更新之前触发,我能够将先前的值存储在名为 previousOption 的组件 属性 中。然后我将另一个名为 currentOption 的 属性 数据绑定到 [(ngModel)] 并使用事件绑定 (valueChanges) 将上一个选项设置为当前选项。然后你可以连接你的 (selectionChange) 来做任何事情。