Angular 2使用默认的单独模型进行选择

时间:2016-12-12 10:35:12

标签: javascript angular angular2-template

NgFor使用其他型号时,我找不到设置默认值或链接到其他型号的方法吗?

我试图绑定的模型是:

"Bookings": {"dates":
[{"date":"3-10-2016","slot":"Full"},
{"date":"4-10-2016","slot":"Full"},
{"date":"5-10-2016","slot":"Afternoon"},
{"date":"6-10-2016","slot":"Morning"}]}

我有另一种选择模型:

lengthsObj = [
 {slot:'Full'},
 {slot:'Morning'},
 {slot:'Afternoon'}
];

我已经尝试了所有可能的组合(模型和价值),我可以想到这个:

<div *ngFor="let date of booking.dates">
 <select *ngIf="true" name="days" [(ngModel)]="date.slot" required>
    <option *ngFor="let length of lengthsObj" [value]="date.slot">
       {{length.slot}}
    </option>
  </select>
</div>

但我没有获得模型或任何默认值的链接。

Here's a plunker

2 个答案:

答案 0 :(得分:1)

您必须使用length.slot option值,如下所示: 查看plnkr

<div *ngFor="let date of booking.dates">
  <select *ngIf="true" name="days" [(ngModel)]="date.slot" required>
    <option *ngFor="let length of lengthsObj" [value]="length.slot">
       {{length.slot}}
    </option>
  </select>
</div>

答案 1 :(得分:1)

通过将date.slot的数据分配到ngValue,您犯了一个错误。只需将ngValue更改为您的plunker中的length.slot即可完美运行:

<select name="days" [(ngModel)]="date.slot" required>
    <option *ngFor="let length of lengthsObj" [ngValue]="length.slot">
        {{length.slot}}
    </option>
</select>