【发布时间】:2020-05-06 05:32:47
【问题描述】:
我创建了一个通用组件来显示表单验证错误消息。如下:
import { Component, OnInit, Input } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'app-err-msg',
template: `<div class="input-error" *ngIf="errorMessage !== null">{{errorMessage}}</div>`,
styleUrls: ['./err-msg.component.css']
})
export class ErrMsgComponent implements OnInit {
@Input() control: FormControl;
@Input() fieldName: FormControl;
isInvalidMsg = ' is invalid';
constructor() { }
get errorMessage() {
for (const propertyName in this.control.errors) {
if (this.control.errors.hasOwnProperty(propertyName) && this.control.touched) {
return this.getValidatorErrorMessage(propertyName, this.control.errors[propertyName]);
}
}
return null;
}
getValidatorErrorMessage(validatorName: string, validatorValue?: any) {
const config = {
'required': this.fieldName + ' is required',
'appPhoneValidate': this.fieldName + this.isInvalidMsg,
'appEmailValidate': this.fieldName + this.isInvalidMsg,
'appPasswordValidate': this.fieldName + ' must containt 8 characters, capital letters, lowercase, numbers and special character.',
'minlength': `minnimum length ${validatorValue.requiredLength}`,
'min': `minumum value ${validatorValue.min}`,
'max': `maximum value ${validatorValue.max}`,
'matchPassword': this.fieldName + ' is mismatched',
'appEqualvalidate': this.fieldName + ' is mismatched',
'appWebValidate': this.fieldName + this.isInvalidMsg,
'appTimeCheckValidate': this.fieldName + this.isInvalidMsg,
};
return config[validatorName];
}
ngOnInit() {
}
}
我已经将此组件用作:
<select
name="timezone"
id="timezoneList"
#timezone="ngModel"
class="form-control text-black"
[(ngModel)]="caseDetail.timezoneId"
required
>
<option [ngValue]="null" disabled>Select Timezone</option>
<option [ngValue]="timezone?.id" *ngFor="let timezone of timezoneList">{{ timezone?.timezoneWithOffset }}</option>
</select>
<app-err-msg [control]="timezone" fieldName="Timezone"></app-err-msg>
在这里我遇到问题,当我单击表单中的取消按钮时,第一次单击会显示验证错误,当我第二次单击取消按钮时,表单提交被取消。这是因为我使用过:this.control.touched。
要解决这个问题,我可以使用if(form.submitted === true),但问题是如何从单个 FormControl 获取 Form 属性,因为我只是传递控件引用而不是 Form 引用。
有什么方法可以获取控件父窗体的属性吗?
【问题讨论】:
-
你想访问 app-err-msg 组件中的父表单吗?
标签: angular validation angular-forms angular-validation