Angular2和Observable:不能绑定到'ngModel',因为它不是'select'的已知属性
编辑:更新Plunkr: http ://plnkr.co/edit/fQ7P9KPjMxb5NAhccYIq?p=preview
这部分工作:
<div *ngFor="let entry of entries | async"> Label: {{ entry.label }}<br> Value: {{ entry.value }} </div>
但是我在select框有问题,错误信息是:
无法绑定到'ngModel',因为它不是'select'的已知属性
整个组件:
//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()); } }
和data.json
[ { "timestamp": 0, "label": "l1", "value": 1 }, { "timestamp": 0, "label": "l2", "value": 2 }, { "timestamp": 0, "label": "l3", "value": 3 } ]
> = RC.5
需要导入ngModel
才能使ngModel
可用
@NgModule({ imports: [BrowserModule /* or CommonModule */, FormsModule, ReactiveFormsModule], ... )} class SomeModule {}
<= RC.4
在config.js
添加
'@angular/forms': { main: 'bundles/forms.umd.js', defaultExtension: 'js' },
在main.ts
添加
import {provideForms, disableDeprecatedForms} from '@angular/forms'; bootstrap(App, [disableDeprecatedForms(),provideForms()])
Plunker例子
也可以看看
请执行以下操作,必须使用[ngValue]
而不是[val]
<select [(ng-model)]="selectValue"> <option *ngFor="let entry of entries | async" [ngValue]="entry.value">{{entry.label}} </option> </select>