如何在Angular2中验证表单?我收到了一个错误。
https://plnkr.co/edit/slhySWT0mJXkloGK1kfO?p=preview
<ion-navbar *navbar>
<ion-title>
Ionic 2
</ion-title>
</ion-navbar>
<ion-content class="has-header">
<form [ngFormModel]="loginForm" (submit)="login($event)">
<ion-input stacked-label>
<ion-label>Username</ion-label>
<input type="text" ngControl="username">
</ion-input>
<ion-input stacked-label>
<ion-label>Password</ion-label>
<input type="password" ngControl="password">
</ion-input>
<div padding>
<button block type="submit" [disabled]="!loginForm.valid">Login</button>
</div>
</form>
</ion-content>
错误
TypeError: Cannot read property 'validator' of undefined
at NgFormModel.ngOnChanges (https://code.angularjs.org/2.0.0-beta.15/angular2.dev.js:17240:73)
at AbstractChangeDetector.ChangeDetector_FormClass_0.detectChangesInRecordsInternal (viewFactory_FormClass:86:59)
答案 0 :(得分:1)
我不熟悉ionic2,所以可能会发生一些我不知道的事情。但是,您似乎没有在FormClass中声明或初始化表单控件。也许试试这个:
export class FormClass {
loginForm: ControlGroup;
constructor(private fb: FormBuilder){
this.loginForm = this.fb.group({
'username': ['', Validators.required],
'password': ['', Validators.required]
});
}
}
您还需要在FormClass中定义一个登录方法来处理您已定义的(提交)绑定。