如何在 Angular 5 / Material 2 中为 mat-select 添加“其他”选项

Gur*_*nig 1 angular

我有一个 angular 5 的 mat-select 下拉菜单。我想要一个“其他”选项,如果选中,则显示带有手动输入的文本字段。我怎样才能做到这一点?我的想法是解决另一个 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>
Run Code Online (Sandbox Code Playgroud)

Ing*_*ürk 6

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

<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>
Run Code Online (Sandbox Code Playgroud)

这依赖于具有 undefined (or null) 的“other”选项value