首页 > 解决方案 > Angular - 仅在值匹配时修补选择下拉列表中的选定值

问题描述

我想<select>用匹配的值修补 Reactive 表单中下拉列表的值。

但是,如果不存在匹配值,<select>则应为空或将默认选择显示为“选择值”,这不应使表单有效。

值匹配的快乐场景有效,但是当值不匹配时,列表中的第一个选项显示为选中,并且表单变为有效。

索引.html

<div class="form-group" *ngIf="{port: port$ | async} as _port$">
    <label for="country">Country</label>
    <select [attr.disabled]="!_port$.port?.length > 0 ? 'disabled' : null" id="country" formControlName="countryCode"
            class="form-control form-control-lg">
      <option disabled value="null">Enter Country type</option>
      <option *ngFor="let type of _port$.port"
              [value]="type.code" [selected]="type.code == countryCode ">{{type.label}}</option>
    </select>
  </div>

索引.ts

this.form.controls[fieldName].patchValue(value);

示例响应 json

port$ = [{
        "code": "1",
        "label": "YEMEN"
      },
      {
        " code ": "2",
        " label ": "ZAMBIA"
      },
      {
        " code ": "3",
        " label ": "ZIMBABWE"
      }]

标签: htmlangularjstypescriptangular7angular-reactive-forms

解决方案


推荐阅读