【问题标题】:Binding two dropdown menu绑定两个下拉菜单
【发布时间】:2019-01-22 06:19:07
【问题描述】:

我正在使用反应驱动形式的方法。我有两个下拉列表,其中列出了两种不同语言的国家列表,用英语和印地语说。 我的用例是,如果我从英语下拉列表中选择任何项目,则从印地语下拉列表中它应该被绑定。 (假设两个下拉菜单的国家代码相同)

我尝试使用 [value] 进行绑定,但它只选择一次,如果我选择不同的值,则相同的值不会反映。 在使用 ngModel 绑定时,出现以下错误 ngModel 不能用于使用父 formGroup 指令注册表单控件。

        <form [formGroup]="userForm" class="user__form">
        <div class="user__dropdown">
          <mat-form-field>
            <mat-select
              placeholder="REGION"
              formControlName="region"
              #region
            >
              <mat-option *ngFor="let region of regions" [value]="region.locationCode">{{
                region.locationName
              }}</mat-option>
            </mat-select>      
          </mat-form-field>
        </div>
      </form>

    <form [formGroup]="secUserForm" class="user__form">
      <div class="user__dropdown">
        <mat-form-field>
          <mat-select
            name="t_region"
            [value]="userForm.get('region').value"
            [disabled]="true"
            [placeholder]="REGION"
          >
            <mat-option *ngFor="let region of transRegions" [value]="region.locationCode">{{
              region.locationName
            }}</mat-option>
          </mat-select>
        </mat-form-field>
      </div>
    </form>

【问题讨论】:

标签: angular


【解决方案1】:

如果您只有两种语言,如果您的国家/地区像这种情况,这种情况很容易

{locationCode:...,locationName1:...,locationName2:...}

您可以通过以下方式更改最后一个选项

<mat-option *ngFor="let region of transRegions" 
      [value]="region.locationCode">
      {{userForm.get('region').value=='en'? region.locationName1
                                          : region.locationName2
      }}
</mat-option>

你可以忘记变化

另一种方法是您拥有类似的数据

transRegion={idiom:'en',regions:[{locationCode:...,locationName:...},...]

请记住,您的 transRegion 可以是一个对象,当更改选择时,您可以添加属性

transRegion:any={}
service.getRegions(county).subscribe)res=>{
     trasnRegion[country]=res
}       

然后你可以转换并制作 *ngFor

<mat-option 
     *ngFor="let region of transRegions[userForm.get('region').value]"
      [value]="region.locationCode">
      {{region.locationName}}
</mat-option>

【讨论】:

    猜你喜欢
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    • 2014-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多