【问题标题】:How to add "other" option to mat-select in Angular 5 / Material 2如何在 Angular 5/Material 2 中添加“其他”选项到 mat-select
【发布时间】:2018-03-10 17:09:40
【问题描述】:

我有一个角 5 的垫选择下拉菜单。我想要一个“其他”选项,如果选中,它会显示一个带有手动输入的文本字段。我怎样才能做到这一点? 我的想法是解决另一个 ngModel 布尔字段,然后它允许 *ng-if 显示文本字段,但即使它可以工作(我不知道如何)它看起来也不是很优雅....

<mat-form-field>
    <mat-select [(ngModel)]="regime" name="regime-input">
        <mat-option [value]=1>daily</mat-option>
        <mat-option [value]=7>weekly</mat-option>
        <mat-option [value]=30>monthly</mat-option>
        <mat-option [value]=0>bei Bedarf</mat-option>
        <mat-option >other</mat-option>
    </mat-select>
</mat-form-field>

【问题讨论】:

  • 你的想法就是实现它的方法。如果您有任何问题,我建议您尝试一下并更新问题。

标签: angular


【解决方案1】:

您可以使用简单的引用来有条件地显示输入:

<mat-form-field>
    <!-- Notice the "#regimeWidget"! -->
    <mat-select [(ngModel)]="regime" name="regime-input" #regimeWidget>
        <mat-option [value]=1>daily</mat-option>
        <mat-option [value]=7>weekly</mat-option>
        <mat-option [value]=30>monthly</mat-option>
        <mat-option [value]=0>bei Bedarf</mat-option>
        <mat-option >other</mat-option>
    </mat-select>
</mat-form-field>

<ng-container *ngIf="!regimeWidget.value">
    <!-- Add your input here -->
    <span>You selected "Other"</span>
</ng-container>

这依赖于具有未定义(或空)value 的“其他”选项。

【讨论】:

  • 感谢您提供出色的解决方案。唯一的问题是“其他”没有显示为选中状态,是否还有这样一个优雅的解决方案?
  • @KrombopulosMichael 似乎 mat-select 就是这样。不过,您可以在下拉列表中添加一个占位符。见stackblitz.com/edit/angular-rwbetq?file=app/…
  • 这个行为解释here
  • 我对代码 here 做了一个小改动,“无”保持选中状态
  • 如果您有 并且想要同时显示两者,则占位符解决方案不起作用。例如。 “你最喜欢的动物”作为标签,“--请选择--”作为未选择案例的值。
猜你喜欢
  • 2018-05-17
  • 1970-01-01
  • 1970-01-01
  • 2018-08-18
  • 2018-05-15
  • 2022-10-13
  • 1970-01-01
  • 2018-07-20
  • 2020-06-26
相关资源
最近更新 更多