angular - 如何以角度的动态形式验证?
问题描述
总之,下面的代码是我的表单代码(请忽略中文,这不重要)
getQuestions() {
const questions: QuestionBase<any>[] = [
new DropdownQuestion({
key: 'homePlace',
label: '籍贯',
options: [
{ key: '杭州', value: '杭州' },
{ key: '温州', value: '温州' },
{ key: '上虞', value: '上虞' },
{ key: '诸暨', value: '诸暨' },
],
order: 3
}),
new TextboxQuestion({
key: 'userName',
label: '用户名',
value: '茶荼先生',
order: 1,
rule: [
Validators.required
]
}),
new TextboxQuestion({
key: 'password',
label: '密码',
order: 2,
rule: [
Validators.required,
Validators.minLength(6),
Validators.maxLength(10),
]
})
];
return questions.sort((a, b) => a.order - b.order);//排序
}
下面的代码是我的html。
<div [formGroup]="form">
<label [attr.for]="question.key">{{question.label}}</label>
<div [ngSwitch]="question.controlType">
<input nz-input *ngSwitchCase="'textbox'" [formControlName]="question.key" [id]="question.key" [type]="question.type">
<nz-select style="width: 120px;" nzAllowClear [id]="question.key" *ngSwitchCase="'dropdown'" [formControlName]="question.key">
<nz-option *ngFor="let opt of question.options" [nzValue]="opt.key" [nzLabel]="opt.value"></nz-option>
</nz-select>
</div>
<div style="color:red;" *ngIf="!isValid">{{question.label}} can't be empty</div>
<div style="color:red;" *ngIf="!minlength">can not less than 6</div>
这里是一个问题。如何验证单个验证规则?例如 minlength。我尝试像这样验证它
get isValid() { return this.form.controls[this.question.key].valid; }
get minlength() { return this.form.controls[this.question.key].errors.minlength; }
该功能isValid
有效。但是,系统提醒我。ERROR TypeError: "this.form.controls[this.question.key].errors is null"
为什么?如果我想验证 minlength 我应该怎么做?
解决方案
您需要做的就是确保错误对象已被填充:
hasError(kind: string) {
return this.form.controls[this.question.key].errors &&
this.form.controls[this.question.key].errors[kind];
}
get minlength() { return this.hasError('minlength'); }
get required() { return this.hasError('required'); }
您的控件也应该相应地实例化
toFormGroup(questions: QuestionBase<any>[]) {
let group: any = {};
questions.forEach(question => {
group[question.key] = new FormControl(question.value || '', question.rule);
^^^^^^^^^^^^^^
sync validators
});
return new FormGroup(group);
}
推荐阅读
- sql - 从数据库中选择错误
- python - 为什么 numba parallel=True 比 parallel=False 慢
- spring-boot - 当属性计数很高时,SpringBoot 动态刷新加载时间过长
- r - 如何使用 for 循环在 ggplot2 中添加“stat_function()”层?
- r - 使用 map 和 map2 映射列表以构造矩阵
- css - 如何让 CodeFlask 代码编辑器样式与 Vuetify 一起正常工作
- java - ipSecurityRestrictions.ipAddress required azure cmd部署错误
- angular - 为 ngrx/data 实体创建选择器
- android - 如何使用 Jetpack Compose 创建 GridView
- python - 不能在 Print() 函数的 Else 语句中使用 End 参数