Angular 表单状态验证器 2

问题描述 投票:0回答:1

我正在尝试编写自定义表单验证器。

我有两个组件主窗体和选项。在选项组件中,我有复选框列表,并且想验证每一行至少检查一个选项。

https://stackblitz.com/edit/stackblitz-starters-quy57f

在选项组件上,我有验证方法,如果某些行无效,我会将其发送到主组件。 在主要组件上,我有属性,它对该发射器做出反应。还有表单验证器,它应该对此 isInvalid 属性做出反应:

<form #inputForm="ngForm" appFormStatusValidator [isInvalid]="isInvalid">

但在验证器内部,即使表单上的属性为 true,isInvalid 属性也为 false(反之亦然)。

你能告诉我,我做错了什么吗?

我希望,当我检查每一行的 option1 时,主表单的状态将为“VALID”。但在控制台日志中我看到:

options component: is INvalid: false main form - isInvalid: false validator: is invalid: true

即使我在主表单组件上将 isInvalid 设置为 false,为什么属性 isInvalid 在验证器内仍为 true?

非常感谢您的建议。

angular validation angular-reactive-forms angular-directive angular2-directives
1个回答
0
投票

这是预期的输出吗,我正在执行与上一个问题类似的方法,但现在我传递选项的 ID 和存在的选项数量,然后使用

some
数组方法,我根据名称验证每个
ngModel
分配给它!

验证指令

import { Directive, Input } from '@angular/core';
import {
  NG_VALIDATORS,
  AbstractControl,
  ValidationErrors,
  FormGroup,
} from '@angular/forms';
import { OptionInterface } from './data.interface';

@Directive({
  selector: '[appFormStatusValidator]',
  providers: [
    {
      provide: NG_VALIDATORS,
      useExisting: FormStatusValidatorDirective,
      multi: true,
    },
  ],
})
export class FormStatusValidatorDirective {
  @Input() appFormStatusValidator: Array<OptionInterface> = [];
  @Input() optionsNumber: number = 0;
  //@Input() formStatusProperty: string = 'valid';

  validate(control: AbstractControl): ValidationErrors | null {
    const formGroup = control as FormGroup;
    let valid = false;
    if (this.appFormStatusValidator.length && !valid && this.optionsNumber) {
      valid = !this.appFormStatusValidator.some((option: OptionInterface) => {
        const optionNames = new Array(this.optionsNumber)
          .fill(null)
          .map((_, index: number) => `option${index}_${option.id}`);
        return !optionNames.some(
          (optionName: string) => control.value[optionName]
        );
      });
    }
    if (formGroup && !valid) {
      return { formStatusInvalid: true }; // Form status is invalid
    } else {
      return null;
    }
  }
}

stackblitz 演示

© www.soinside.com 2019 - 2024. All rights reserved.