【问题标题】:angular reactive form - bind another property other than [value]角度反应形式 - 绑定 [value] 以外的另一个属性
【发布时间】:2017-07-25 17:57:17
【问题描述】:

我有一个带有选择框的角度反应形式,如下所示:

<select formControlName="incomeSourceId">
    <option value="" disabled >Select a source</option>
    <option *ngFor="let source of primarySourceIncome"  [value]="source.value">{{source.viewValue}}</option>
</select>

我想根据下拉选择显示/隐藏部分。到目前为止,我有:

<div class="row" [hidden]="applicationForm.get('incomeSourceId').value !== '1'"></div>
<div class="row" [hidden]="applicationForm.get('incomeSourceId').value !== '2'"></div>

组件:

this.applicationForm = this.fb.group({     
  incomeSourceId: ['', [Validators.required, Validators.minLength(1), Validators.maxLength(50)]]   

})

但是,这可行,我的逻辑是基于值,这是从服务器返回的 ID。我更愿意建立这个逻辑来检查{{source.viewValue}},这不会改变。如何将另一个属性绑定到表单&lt;option&gt;? NgModel 在表单组中不起作用。

【问题讨论】:

  • 所以你的意思是说[value]在这种情况下不起作用
  • 正确。 [value]="source.value" 设置为从服务器填充并发送到服务器的 id。它可能会发生变化,而 {{source.viewValue}} 将保持不变并且是一个字符串,例如“Employed”
  • 是否有任何答案适合您的需要? :)

标签: javascript angular


【解决方案1】:
<select formControlName="incomeSourceId">
    <option value="" disabled >Select a source</option>
    <option *ngFor="let source of primarySourceIncome"  [ngValue]="source.value">{{source.viewValue}}</option> // change to [ngValue]
</select>

如果值不是字符串,则必须使用 [ngValue]="..."。 [value]="..." 只支持字符串。

【讨论】:

    【解决方案2】:

    您可以使用当前 primarySourceIncome 的索引作为值:

    <option *ngFor="let source of primarySourceIncome; index as i" [value]="i">{{source.viewValue}}</option>
    

    如果该选择输入的值对于保存很重要,那么在保存之前,您需要在 primarySourceIncome 中查找该索引并将该值设置为应有的值。

    【讨论】:

      【解决方案3】:

      这似乎是一种解决方法,但我认为它仍然很干净。

      在您的选择中有一个(change) 事件,我们只需使用find() 在您的数组中查找带有value 的对象。这样我们就可以得到对应的viewValue 到那个value。在这种情况下,当名称很长时,我喜欢将它们存储在变量中,以便于使用,所以对于您的表单控件,我会在构建表单后执行此操作

      this.idCtrl = this.applicationForm.get('incomeSourceId');
      

      然后select触发的change事件,我们只需将所选对象中的viewValue分配给变量viewVal

      findViewValue() {
        this.viewVal = this.primarySourceIncome.find(x => 
           x.value == this.idCtrl.value).viewValue
      }
      

      既然你提到viewValue 不会改变,我们这里只是在模板中使用了字符串文字。我也在这里使用了[ngSwitch],我认为看起来更干净:) 例如,模板可能如下所示:

      <div [ngSwitch]="viewVal">
        <div *ngSwitchCase="'Employee'">Employee</div>
        <div *ngSwitchCase="'Manager'">Manager</div>
      </div>
      

      这也消除了在模板中调用“不必要的”get 请求。

      【讨论】:

        猜你喜欢
        • 2021-11-30
        • 2021-02-08
        • 2018-12-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多