2016-08-16 40 views
0

我想为ngFormControl创建一个最小的例子,因为我不能让它在我正在编写的新组件中工作,而在旧的它工作得很好,我不能找到差异。下面是一个小例子,在那里我获得绑定错误:ngFormControl没有正确地绑定

import {Component, NgModule} from '@angular/core'; 
import {BrowserModule} from '@angular/platform-browser'; 
import {Control} from "@angular/common"; 
import { FormsModule } from '@angular/forms'; 

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div> 
     <input class="form-control" type="text" [ngFormControl]="searchInput"> 
    </div> 
    ` 
}) 
export class App { 
    private searchInput = new Control(); 
} 

@NgModule({ 
    imports: [ BrowserModule, FormsModule ], 
    declarations: [ App ], 
    bootstrap: [ App ] 
}) 
export class AppModule {} 

这里也是表示问题Plunkr。根据我的理解,它也应该可以在不导入FormsModule的情况下工作,因为FormsModule只需要与ngModel进行双向绑定。那是对的吗?

干杯

回答

1

在rc.3这种方式已经过时,你现在应该使用ngModel。

你应该看看这个tutorial

+0

嘿,文档并没有说它的depricated:https://angular.io/docs/ts/latest/api/common/index/NgFormControl-directive.html。为什么我不想使用ngModel的主要问题是,我无法使用Controls提供的debounceTime和distinctUntilChanged方法。 – Tom

+0

您应该查看此文档https://docs.google.com/document/u/0/d/1RIezQqE4aEhBRmArIAS1mRIZtWFf6JxN_7B4meyWK0Y/pub。 –

1

ngFormControl指令不会对角2形式

进行更改后的新版本(0.30.0)存在应该解决您的问题:

app.ts

//import FormControl from angular/forms 
import { FormsModule, FormControl } from '@angular/forms'; 
import { ReactiveFormsModule } from '@angular/forms' 

@Component({ 
.. 
.. 
//change [ngFormControl] to [formControl] 
<input class="form-control" type="text" [formControl]="searchInput"> 
.. 
.. 

export class App { 
//change new Control(); => new FormControl(); 
private searchInput = new FormControl(); 
} 

//add ReactiveFormsModule to the @NgModule imports metadata 
@NgModule({ 
     imports: [ BrowserModule, FormsModule, ReactiveFormsModule ], 
     declarations: [ App ], 
     bootstrap: [ App ] 
}) 

Plunkr