如何以角的动态形式进行验证?

时间:2018-08-08 02:51:34

标签: 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"。为什么? 如果我想验证最小长度怎么办?

1 个答案:

答案 0 :(得分:0)

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

-keep

另外,您的控件也应在

中实例化。
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'); }

Ng-run Example