我在我的应用程序中使用角度2表单,我已根据给定的链接创建表单.
https://angular.io/docs/ts/latest/guide/forms.html
在这个验证和使用表单API,我已设置ngModel值,如#name =“id”#id =“ngModel”,并抛出脚本错误.但如果我将#id =“ngModel”设置为#id =“ngForm”,它就会解决.但对于我的情况,我必须将我的模型值设置为ngModel.
下面是我的html页面.
<form (ngSubmit)="onSubmit()" #myForm="ngForm"> <div class="form-group"> <label class="control-label" for="id">Employee ID</label> <input type="text" class="form-control" required [(ngModel)]="model.id" #name="id" #id="ngModel" > <div [hidden]="id.valid || id.pristine" class="alert alert-danger"> Employee ID is required </div> </div> <div class="form-group"> <label for="name">Employee Name</label> <input type="text" class="form-control" [(ngModel)]="model.name" name="name" #name="ngModel" required> <div [hidden]="name.valid || name.pristine" class="alert alert-danger"> Employee ID is required </div> </div> <div class="form-group"> <label for="DOJ">DOJ</label> <input class="form-control" required [(ngModel)]="model.DOJ" name="DOJ" #DOJ="ngModel" /> <div [hidden]="DOJ.valid || DOJ.pristine" class="alert alert-danger"> DOJ is required </div> </div> <button type="submit" class="btn btn-default" [disabled]="!myForm.form.valid">Submit</button> </form>
以下是我的问题.
EXCEPTION: Template parse errors: There is no directive with "exportAs" set to "ngModel" (" <div> <h1>My Form</h1> <form (ngSubmit)="onSubmit()" [ERROR ->]#myForm="ngModel"> <div class="form-group> <label class="control-label" for="id">Employee"):AppComponent@3:34
我已经检查了更多的问题和答案,他们中的大多数都说将angular2版本更新为RC4,所以我已经将我的应用程序更新为rc4,但我仍然面临这个问题.
以下是我的ts文件:
import {Component} from '@angular/core'; import { disableDeprecatedForms,provideForms,NgForm} from '@angular/forms'; import {CORE_DIRECTIVES,FORM_DIRECTIVES,FormBuilder,Validators,Control,ControlGroup } from '@angular/common'; @Component({ selector: 'ej-app',templateUrl: 'app/app.component.html',directives: [ CORE_DIRECTIVES,FORM_DIRECTIVES] }) export class AppComponent { model = new Employees(null,'',''); onSubmit() { alert("values submitted")} constructor() { } } export class Employees { constructor( public id: number,public name: string,public DOJ: String ) { } }
解决方法
不要混合新旧表单模块.
import {CORE_DIRECTIVES,ControlGroup } from '@angular/common';
进口形成来自@ angular / common的东西.如果您使用新表格
bootstrap(AppComponent,[disableDeprecatedForms(),provideForms()])
然后改用
import {FORM_DIRECTIVES,ControlGroup } from '@angular/forms';