【问题标题】:Getting object properties via ngModel select list in Angular 2?通过Angular 2中的ngModel选择列表获取对象属性?
【发布时间】:2016-10-06 18:22:49
【问题描述】:

我在获取已从 Angular 2 (RC1) 中的选择列表中选择的对象的属性时遇到问题。采用以下语法:

<select required [(ngModel)]="model.plan">
  <option selected="selected" disabled>Plan...</option>
  <option *ngFor="#plan of plans" [value]="plan">{{ plan.name }}</option>
</select>

其中plans 定义为对象数组:

[{ name: 'Plan 1' }, { name: 'Plan 2' }]

如果您尝试输出所选对象的其中一个键的值,则不会显示任何内容:

<p>{{ model.plan?.name }}</p> // Shows nothing if a plan is selected

Here is a fork of the Angular2 form live demo,显示这个问题。从选择列表中选择“Plan 2”,看到没有任何显示。

这是怎么回事?

【问题讨论】:

    标签: angular angular2-forms


    【解决方案1】:

    要将对象用作值,请使用 [ngValue] 而不是 [value][value] 仅支持字符串 id。

    <select required [(ngModel)]="model"> <!-- <== changed -->
      <option selected="selected" disabled>Plan...</option>
      <option *ngFor="#plan of plans" [ngValue]="plan">{{ plan.name }}</option>
    </select>
    

    Plunker example

    model 需要指向plans 中的一个元素才能用作默认值(它必须是相同的实例,而不是包含相同值的另一个实例)。

    【讨论】:

      【解决方案2】:

      据我所知,双向绑定到select 仍然存在问题。所以试试这个:

      模板

      <select required [(ngModel)]="model.plan" (change)="setPlan($event.target.value)">
          <option selected="selected" disabled>Plan...</option>
          <option *ngFor="#plan of plans" [value]="plan.name">{{ plan.name }}</option>
      </select>
      

      组件类

      setPlan(value) {
          //if you're on older versions of ES, use for-in instead
          var plan = this.plans.find(p => p.name = value);
      
          if(plan) { this.model.plan = plan; }
      }
      

      无法尝试,由于某种原因,plunkr 从来没有为我工作过。

      【讨论】:

        猜你喜欢
        • 2014-02-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多