编辑:更新了Plunkr:http://plnkr.co/edit/fQ7P9KPjMxb5NAhccYIq?p=preview
这部分有效:
<div *ngFor="let entry of entries | async">
Label: {{ entry.label }}<br>
Value: {{ entry.value }}
</div>
但我对选择框有问题,错误信息是:
Can't bind to 'ngModel' since it isn't a known property of 'select'
The whole Component:
//our root app component
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
import {HTTP_PROVIDERS, Http} from '@angular/http';
import 'rxjs/Rx';
import {Observable} from 'rxjs/Rx';
@Component({
selector: 'my-app',
providers: [HTTP_PROVIDERS],
template: `
<select [(ngModel)]="selectValue" name="selectValue">
<option *ngFor="let entry of entries | async"
[value]="entry.value">{{entry.label}}</option>
</select>
<div *ngFor="let entry of entries | async">
Label: {{ entry.label }}<br>
Value: {{ entry.value }}
</div>
`,
directives: [NgFor]
})
export class App {
entries: any = {};
selectValue:any;
constructor(private _http: Http) {
this.entries = this._http.get("./data.json")
.map(res => res.json());
}
}
and data.json
[
{
"timestamp": 0,
"label": "l1",
"value": 1
},
{
"timestamp": 0,
"label": "l2",
"value": 2
},
{
"timestamp": 0,
"label": "l3",
"value": 3
}
]
6 回答
>= RC.5
需要导入
FormsModule
以使ngModel
可用<= RC.4
在
config.js
添加在
main.ts
添加Plunker example
也可以看看
在app.modules.ts之后
放:
然后在
插入FormsModule类似于:
尽管我已经在我的组件的
*.module.ts
文件中导入了FormsModule
,但我的测试套件中发生了这种情况 .在我的
*.component.spec.ts
文件中,我需要将FormsModule
和ReactiveFormsModule
添加到configureTestingModule
中的导入列表中:这解决了我的情况 .
您需要将以下内容添加到
app.module.ts
文件中 .和,
执行以下操作,您必须使用
[ngValue]
而不是[val]
导致上述错误的原因是您尚未导入FormsModule,而且还存在于FormsModule包中的ngModel,因此,为了摆脱此错误,请添加
import {FormsModule} from '@angular/forms'
并在app.module.ts类的导入中添加FormsModule .