循序渐进.
当我们使用VALIDATE创建自定义表单控件时,函数VALIDATE应该返回或返回一个对象,或者返回空(如果没有错误).
public validate(c: FormControl) {
const errors: any[] = [];
if (!this.control) this.control = c;
this.errors &&
this.errors.forEach((error) => {
if (error.type == 'required') {
if (!c.value) {
errors.push({ required: true, message: error.message });
}
}
});
return errors.length ? { error: errors } : null;
}
请参见返回一个具有唯一属性"Error"的对象,该属性是一个错误array.
这个错误是内部控件的错误not--您在定制输入中输入--否则就是"Parent"中声明的FormControl
.因此,要在自定义表单控件内迭代此错误,我们需要"获取它".
通常,您可以使用构造函数
constructor(@Optional() @Self() public ngControl: NgControl){
if (this.ngControl != null) {
this.ngControl.valueAccessor = this;
}
}
但是,由于我们只需声明一个验证函数,并在验证函数中为其赋值
control!: AbstractControl;
public validate(c: FormControl) {
if (!this.control) this.control = c;
...rest of the code..
}
最后一种方法是迭代此错误
<ng-container *ngIf="control?.touched || control?.dirty">
<ng-container *ngFor="let error of control?.errors?.error">
<div class="error-text">
{{ error.message }}
</div>
</ng-container>
</ng-container>
你的forked stackblitz
注意:请注意,您不必将validators
加到您的FormControls
上
在您的代码中:
registrationForm = this.fb.group({
username: [''],
password: [''],
});
update只在需要时才发送,我们需要使用类似于
public validate(c: FormControl) {
const errors: any[] = [];
if (!this.control) this.control = c;
cons errorRequired==!c.value && this.errors?this.errors.find(x=>x=='required'):null
if (errorRequired)
return [{required:true,message:errorRequired.message}]
this.errors &&
this.errors.forEach((error) => {
if (error.type == 'required') {
if (!c.value) {
errors.push({ required: true, message: error.message });
}
}
});
return errors.length ? { error: errors } : null;