我来找你谈一下与Angular Material相关的问题。实际上,我认为这是一个问题,但我更喜欢先寻找误解。
我的问题首先与上下文有关,我试图创建一个简单的表单,包含两个输入框:密码和确认密码。
user-form.component.ts
this.newUserForm = this.fb.group({
type: ['', Validators.required],
firstname: ['', Validators.required],
lastname: ['', Validators.required],
login: ['', Validators.required],
matchingPasswordsForm: this.fb.group(
{
password1: ['', Validators.required],
password2: ['', Validators.required],
},
{
validator: MatchingPasswordValidator.validate,
},
),
mail: ['', [Validators.required, Validators.pattern(EMAIL_PATTERN)]],
cbaNumber: [
'411000000',
[Validators.required, Validators.pattern(CBANUMBER_PATTERN)],
],
phone: ['', [Validators.required, Validators.pattern(PHONE_PATTERN)]],
}
我对匹配密码表单 FormGroup 感兴趣。您可以在其中看到验证器。
这里是验证器:
matching-password.validator.ts
export class MatchingPasswordValidator {
constructor() {}
static validate(c: FormGroup): ValidationErrors | null {
if (c.get('password2').value !== c.get('password1').value) {
return { matchingPassword: true};
}
return null;
}
}
and the HTML.
user-form.component.html
<div class="row" formGroupName="matchingPasswordsForm">
<mat-form-field class="col-md-6 col-sm-12">
<input matInput placeholder="Mot de passe:" formControlName="password1">
<mat-error ngxErrors="matchingPasswordsForm.password1">
<p ngxError="required" [when]="['dirty', 'touched']">{{requiredMessage}}</p>
</mat-error>
</mat-form-field>
<mat-form-field class="col-md-6 col-sm-12">
<input matInput placeholder="Confirmez" formControlName="password2">
<mat-error ngxErrors="matchingPasswordsForm.password2">
<p ngxError="required" [when]="['dirty', 'touched']">{{requiredMessage}}</p>
</mat-error>
<!-- -->
<!-- problem is here -->
<!-- -->
<mat-error ngxErrors="matchingPasswordsForm" class="mat-error">
<p ngxError="matchingPassword" [when]="['dirty', 'touched']">{{passwordMatchErrorMessage}}</p>
</mat-error>
<!-- ^^^^^^^^^^^^^^^^ -->
<!-- /problem is here -->
<!-- -->
</mat-form-field>
</div>
我已在有趣的代码周围添加了注释。
现在,一些解释:使用标签时,当触摸密码2时,我的错误会被显示出来: 刚刚触摸了密码2 但是,当我输入错误的密码时,错误不再显示: 错误的密码2 起初我以为我误解了自定义验证器的使用。但当我用替换错误提示时,整个程序就完美地运行了!
<mat-hint ngxErrors="matchinghPasswordsForm">
<p ngxError="matchingPassword" [when]="['dirty', 'touched']">{{passwordMatchErrorMessage}}</p>
</mat-hint>
我希望我表达清楚了,在在material design的github上发布问题之前,我真的想知道您的观点。
如果我误解了什么,请指出我错过了什么。
最后一件事,我的测试是使用ngxerrors和*ngif完成的。为了更易读,我的代码示例只使用ngxerrors。
mat-error
的样式而不必处理这些问题? - mel