这看起来应该是非常直接的。在stepper中,您正在收集信息,并且您希望确保电子邮件是电子邮件。但是似乎共享的'form‘标签导致了一些问题,比如错误检查器搞砸了,不能工作了?
进一步澄清..。这个问题似乎实际上存在于以下标记元素中……
formControlName="emailCtrl"
当我删除这一行,并从.ts (emailCtrl:'',Validators.required,)中删除它的兄弟行时,错误检查开始工作。然而,这意味着步进器不能验证这一步是必需的。
如何确保stepper验证条目,同时确保ErrorStateMatcher正常工作?
这是我的组合HTML...
<mat-step [stepControl]="infoFormGroup">
<form [formGroup]="infoFormGroup">
<ng-template matStepLabel>Profile Information</ng-template>
<div>
<!-- <form class="emailForm"> -->
<mat-form-field class="full-width">
<input matInput placeholder="Username" [formControl]="emailFormControl"
formControlName="emailCtrl"
[errorStateMatcher]="infoMatcher">
<mat-hint>Must be a valid email address</mat-hint>
<mat-error *ngIf="emailFormControl.hasError('email') && !emailFormControl.hasError('required')">
Please enter a valid email address for a username
</mat-error>
<mat-error *ngIf="emailFormControl.hasError('required')">
A username is <strong>required</strong>
</mat-error>
</mat-form-field>
<!-- </form> -->
</div>
<button mat-button matStepperPrevious>Back</button>
<button mat-button matStepperNext>Next</button>
</form>
</mat-step>
如你所见,我已经注释掉了电子邮件槽的嵌套'form‘。在测试中,我尝试了注释,而不是注释掉。无论哪种方式,错误检查都不能正常工作。
以下是一些相关的.ts代码片段...
import { FormControl, FormGroupDirective, NgForm, Validators } from '@angular/forms';
import { FormBuilder, FormGroup } from '@angular/forms';
import { ErrorStateMatcher } from '@angular/material/core';
export class Pg2ErrorStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
const isSubmitted = form && form.submitted;
return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));
}
}
...
export class Pg2Dialog {
...
emailFormControl = new FormControl('', [
Validators.required,
Validators.email,
]);
infoMatcher = new Pg2ErrorStateMatcher();
...
this.infoFormGroup = this._formBuilder.group({
emailCtrl: ['', Validators.required],
});
发布于 2018-08-17 21:54:17
我想我已经弄明白了。ErrorStateMatcher需要命名的表单控件。在本例中,它是emailFormControl。这被声明如下...
emailFormControl = new FormControl('', [
Validators.required,
Validators.email,
]);
此外,stepper需要一个命名的表单组,该表单组本身声明了一个新的表单控件。在本例中,它是emailCtrl。它被声明如下...
this.infoFormGroup = this._formBuilder.group({
emailCtrl: ['', Validators.required],
});
要让stepper表单控件使用ErrorStateMatcher表单控件,只需将方括号放在.group赋值中并将emailFormControl分配给emailCtrl即可。像这样..。
this.infoFormGroup = this._formBuilder.group({
emailCtrl: this.emailFormControl
});
我用类似的问题在不同的代码段中测试了它,它在两个地方都能工作!
https://stackoverflow.com/questions/51899195
复制相似问题