注册表单,字段被填写并发送到服务器。服务器发送电子邮件已忙的响应。然后我想将电子邮件字段突出显示为无效,但该字段中的值支持电子邮件格式并被验证器识别为有效。
尝试了不同的变化
this.registerForm.controls['email'].setErrors({ invalid: true, valid: false })
但该领域没有着色。怎么做?
注册.component.ts
export class RegistrationComponent implements OnInit {
public registerForm: FormGroup
public spinnerShow = false
public errMsg: String
public bothErrMsg: String.
constructor(
...
private matDialogRef: MatDialogRef<RegistrationComponent>,
private fb: FormBuilder
) {}
ngOnInit() {
this.registerForm = this.fb.group({
email: ['', [FormValidationService.emailValidator]],
password: this.fb.group({
pwd: ['', [FormValidationService.passwordValidator]],
confirm: ['', [FormValidationService.passwordValidator]],
}, {validator: FormValidationService.confirmValidator('pwd', 'confirm')}),
username: ['', [FormValidationService.shortStringValidator]],
})
}
register() {
this.spinnerShow = !this.spinnerShow
const regData = this.registerForm.value
regData.confirm = this.registerForm.value.password.confirm
regData.password = this.registerForm.value.password.pwd
this.auth.registration(regData).subscribe(
(res: any) => {
if (res.error) {
this.spinnerShow = !this.spinnerShow
const messages = res.messages
for (const key in messages) {
if (messages.hasOwnProperty(key)) {
if (key === 'both') {
this.bothErrMsg = messages[key]
this.registerForm.controls['email'].setErrors({ notUnique: true })
} else {
this.registerForm.controls[key].setErrors({ errMsg: messages[key] })
}
}
}
} else {
this.lc.setItem('user', res.user)
this.matDialogRef.close()
}
},
error => {
console.log(error) // TODO
this.spinnerShow = !this.spinnerShow
}
)
}
}
注册.component.html
<div class="container">
<h3>Register new user.</h3>
<form [formGroup]="registerForm" novalidate>
<mat-form-field>
<input matInput formControlName="email" placeholder="Email" type="email" required>
<mat-error *ngIf="registerForm.controls.email.hasError('errMsg') && registerForm.controls.email.touched">
{{ registerForm.get('email').getError('errMsg') }}
</mat-error>
</mat-form-field>
<div class="error" *ngIf="bothErrMsg !== undefined">{{ bothErrMsg }}</div>
<button mat-raised-button color="primary" [disabled]="registerForm.invalid == true" (click)="register()">Sign Up</button>
</form>
</div>
来自服务器的错误(两者都是 serverErrorMsg 尚未重命名为正常名称)。服务器返回 200 代码和错误消息(如果有)。