角材料选择奇怪的问题

时间:2020-05-07 13:45:30

标签: angular angular-material

我使用出现了一个奇怪的问题。要填充,我有一个像这样的JSON:

values: [{'id' : 'male', 'label' : 'Homme'}, {'id': 'female', 'label' : 'Femme'}]

我的HTML如下所示:

<div class="col-md-2" *ngIf="type === 'select'">
    <mat-form-field>
        <select matNativeControl>
             <option *ngFor="let options of values"
                     [value]="options.id"
                     [selected]="options.id == selectedValue">
                {{options.label}}
             </option>
         </select>
        <mat-hint align="end">{{ label }}</mat-hint>
    </mat-form-field>
</div>

如果selectedValue等于female,则没有问题。但是,如果它等于male,则没有选择的选项,我找不到原因

有帮助吗?

谢谢

2 个答案:

答案 0 :(得分:1)

我不确定当前发生的情况,但是我认为,如果您尝试为选择设置默认值,Set default option in mat-select会有所帮助。

2种方式的绑定(如链接所示)或使用具有预设值的反应形式可能是您最好的选择。

祝你好运!

答案 1 :(得分:0)

首先,您应该在此处使用mat-select。因为,如果您使用mat-form-field,则必须在其中调用mat-select或任何其他mat-field。然后,您应该在[(value)]内的mat-select值上使用selectedValue,如下所示。

<div class="col-md-2" *ngIf="type === 'select'">
    <mat-form-field>
       <mat-select matInput formControlName="yourId" [(value)]="selectedValue"
                    placeholder="Your text">
          <ng-container *ngFor="let options of values">
            <mat-option value="{{options.id}}">{{options.label}}</mat-option>
          </ng-container>
        </mat-select>

    </mat-form-field>

</div>