我想通过运气在我的自定义控件中显示set te错误消息。该消息始终为空!我想念什么? onSelectedCC(event:any)//被调用以打开/关闭电话验证器
HTML
<div class="form-group col-xs-3 col-md-3"
[ngClass]="{
'has-error':(ersaForm.get('phone').touched || ersaForm.get('phone').dirty ) &&
!ersaForm.get('phone').valid
}">
<label for="phoneLabel" class="control-label">Phone</label>
<input type="tel" formControlName="phone" pattern="^[0-9-+s()]*$" class="form-control" id="phoneLabel" placeholder="Phone">
<span class="help-block" *ngIf="(ersaForm.get('phone').touched || ersaForm.get('phone').dirty ) &&
ersaForm.get('phone').errors">
<span *ngIf="ersaForm.get('phone').errors.customVal">
<!--Phone Number does not exist.-->
</span>
</span>
TS(客户控制正常,但消息为空)
return (c: AbstractControl): { [key: string]: boolean } | null => {
let dataForm = c.parent;
c.setErrors(null);
var phoneVal = "";
if (c.value.length != 10) {
c.setErrors({ 'incorrect phone format': true });
return { 'customVal': true };
}
if (c.value != undefined && val == -1 && val != '') {
c.setErrors({ 'Phone Number does not exist.': true });
return { 'customVal': true };
};
return null;
};
}
this.ersaForm = this._fb.group({
phone: '',
});
onSelectedCC(event: any)//this called to turn on/off phone validator
{
const phoneControl = this.ersaForm.get('phone');
let cc = event.value.name;
if (cc == '1111' )
{
phoneControl.setValidators([Validators.required, phoneCheck(this.customVal)]);
}
else {
phoneControl.clearValidators();
}
phoneControl.updateValueAndValidity();
}
答案 0 :(得分:0)
您的错误消息文本似乎已被注释掉:
<!--Phone Number does not exist.-->
尝试一下:
<span class="help-block" *ngIf="(ersaForm.get('phone').touched || ersaForm.get('phone').dirty ) && ersaForm.get('phone').invalid">
<span *ngIf="ersaForm.get('phone').hasError('customVal')">
Phone Number does not exist
</span>
</span>
答案 1 :(得分:0)
您要设置错误以形成组级别。将错误设置为单个formControl
return (c: AbstractControl): { [key: string]: boolean } | null => {
let dataForm = c.parent;
c.setErrors(null);
var phoneVal = "";
if (c.value.length != 10) {
c.get('phone').setErrors({ 'incorrect phone format': true });
return { 'customVal': true };
}
if (c.value != undefined && val == -1 && val != '') {
c.get('phone').setErrors({ 'Phone Number does not exist.': true });
return { 'customVal': true };
};
return null;
};
}