首页 > 解决方案 > 如何以角度的动态形式验证?

问题描述

总之,下面的代码是我的表单代码(请忽略中文,这不重要)

 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 我应该怎么做?

标签: angular

解决方案


您需要做的就是确保错误对象已被填充:

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);
}

Ng 运行示例


推荐阅读