在使用TypeScript的Angular2-forms框架时,我一直得到这个错误:

没有将exportAs设置为ngForm的指令

这是我的代码

项目依赖关系:

  "dependencies": {
    "@angular/common": "2.0.0-rc.6",
    "@angular/compiler": "2.0.0-rc.6",
    "@angular/core": "2.0.0-rc.6",
    "@angular/forms": "2.0.0-rc.6",
    "@angular/http": "2.0.0-rc.6",
    "@angular/platform-browser": "2.0.0-rc.6",
    "@angular/platform-browser-dynamic": "2.0.0-rc.6",
    "@angular/router": "3.0.0-rc.2",
    "ng2-bootstrap": "^1.1.1",
    "reflect-metadata": "^0.1.8",
    "core-js": "^2.4.0",
    "es6-module-loader": "^0.17.8",
    "rxjs": "5.0.0-beta.11",
    "systemjs": "0.19.27",
    "zone.js": "0.6.17",
    "jquery": "3.0.0",
  }

这是登录模板:

<form #loginForm="ngForm" (ng-submit)="authenticate(loginForm.value)">
</form>

...和登录组件:

import { Component } from '@angular/core';
import {Http, Headers}  from '@angular/http';
@Component({
    moduleId: module.id,
    selector: 'login-cmp',
    templateUrl: 'login.component.html'
})
export class LoginComponent {
  constructor($http: Http) {
    this.$http = $http;
  }
  authenticate(data) {
   ... 
  }
}

我有这个错误:

zone.js?1474211973422:484 Unhandled Promise rejection: Template parse errors:    
There is no directive with "exportAs" set to "ngForm" ("
            <form [ERROR ->]#loginForm="ngForm" 
(ngsubmit)="authenticate(loginForm.value)">

当前回答

你应该用ctrl+c终止app,然后用ng serve重新运行它,如果你没有将FormsModule包含到你的app.module文件导入数组中,然后再添加它,angular不会知道它,它不会重新扫描模块,你应该重新启动app,这样angular就可以看到新模块被包含了,之后它将包含模板驱动方法的所有功能

其他回答

.HTML文件<form (ngSubmit)="addIngredients(f)"# f = " ngForm " > .ts文件@ViewChild('f', {static: false})

在HTML中更新ngForm到ngForm对我有用

你不仅要将FormsModule导入到根模块AppModule中,还要导入到所有使用angular forms指令的子模块中。

// SubModule A

import { CommonModule } from '@angular/common';
import { FormsModule }   from '@angular/forms';

@NgModule({
  imports: [
    CommonModule,
    FormsModule      //<----------make sure you have added this.
  ],
  ....
})

(以防别人也像我一样瞎) 形成增值!确保使用<form>标签

不工作:

<div (ngSubmit)="search()" #f="ngForm" class="input-group">
    <span class="input-group-btn">
      <button class="btn btn-secondary" type="submit">Go!</button>
    </span>
    <input type="text" ngModel class="form-control" name="search" placeholder="Search..." aria-label="Search...">
</div>

效果非常好:

 <form (ngSubmit)="search()" #f="ngForm" class="input-group">
     <span class="input-group-btn">
       <button class="btn btn-secondary" type="submit">Go!</button>
     </span>
     <input type="text" ngModel class="form-control" name="search" placeholder="Search..." aria-label="Search...">
</form>
import { FormsModule,ReactiveFormsModule }from'@angular/forms';

imports:[
    BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
    HttpClientModule,
    FormsModule,
    ReactiveFormsModule/*This one in particular*/,...
],

在app.module.ts中永久解决诸如“无法绑定[formGroup]或没有export as指令”之类的错误。

import { FormsModule }   from '@angular/forms';

@NgModule({
  imports: [FormsModule],
  ...
})