【发布时间】:2018-03-11 12:02:27
【问题描述】:
我在使用 Angular 中的反应式表单验证嵌套表单时遇到问题。我有一个正常工作的注册表单,但是在我添加表单组以分别检查有效性之后,我得到了一些错误。这些错误是因为验证器仅适用于主窗体而不是嵌套窗体。我试图访问嵌套表单的值,但我发现表单的值是未定义的。
组件.ts
import { Component, OnInit } from "@angular/core";
import { FormBuilder, FormGroup, Validators, FormControl } from "@angular/forms";
@Component({
selector: 'my-page-sign-up',
styleUrls: ['./sign-up.component.scss'],
templateUrl: './sign-up.component.html'
})
export class PageSignUpComponent implements OnInit {
myForm: FormGroup;
constructor(private fb: FormBuilder) {
this.myForm = this.fb.group({
'emailPass': this.fb.group({
email: ['', [
Validators.required,
Validators.email
]],
password: ['', Validators.required],
confirmPassword: ['', Validators.compose([
Validators.required,
this.isEqualPassword.bind(this)
])],
}),
})
}
isEqualPassword(control: FormControl): {[s: string]: boolean} {
if (!this.myForm.controls) {
return {passwordsNotMatch: true};
}
if (control.value !== this.myForm.controls['password'].value) {
return {passwordsNotMatch: true};
}
}
}
html
<form [formGroup]="myForm" (ngSubmit)="onSignup()">
<div formGroupName="emailPass" class="form-group">
<md-input-container class="col-md-6 md-icon-left">
<md-icon class="material-icons">mail_outline</md-icon>
<input formControlName="email" mdInput #email type="email" name="email" class="form-control" placeholder="Email">
<!--md-hint *ngIf="!myForm.get(['emailPass', 'email']).pristine && myForm.hasError('noEmail', 'email')">Invalid mail address</md-hint-->
</md-input-container>
<md-input-container class="col-md-6 md-icon-left no-margin-bottom">
<md-icon class="material-icons">lock_outline</md-icon>
<input required mdInput formControlName="password" type="password" class="form-control" id="password" name="password" placeholder="Contraseña">
</md-input-container>
<md-input-container class="col-md-6 md-icon-left no-margin-bottom">
<md-icon class="material-icons">lock_outline</md-icon>
<input required mdInput type="password" formControlName="confirmPassword" class="form-control" name="password" placeholder="Confirmar Contraseña">
</md-input-container>
</div>
<button md-raised-button type="submit">Siguiente</button>
所以,我有两个问题。第一个是如何解决我在尝试验证密码和电子邮件时遇到的错误。第二个是知道如果嵌套表单(emailPass 表单)无效,我该如何禁用按钮。
感谢您一如既往的帮助!
【问题讨论】:
标签: angular typescript angular-reactive-forms