【问题标题】:Get sibling AbstractControl from Angular reactive FormArray - Custom Validation从 Angular 反应式 FormArray 获取同级 AbstractControl - 自定义验证
【发布时间】:2019-04-11 05:27:52
【问题描述】:

我在 Angular 中有一个使用响应式表单的联系表单。该表单包含firstNamelastName 和一个address 数组。每个地址表单组都包含一个复选框,如果选中该复选框,则需要对 State 文本框进行强制验证,以及最小和最大字符长度。

我编写了一个自定义验证器,即“stateValidator”,并尝试获取同级元素“isMandatory”,但无法获得控制权。

我尝试了以下方法

  • control.root.get('isMandatory'); - 它返回null
  • control.parent.get('isMandatory'); - 抛出异常

我在 stackoverflow 中找到了一些链接,但没有可用的答案,并且一些答案没有给出解决方案,例如上面的代码:control.root.get('isMandatory'); 我是从其中一个视频教程中得到的,但没有任何效果。

StackBlitz 中提供了完整的工作源代码:https://stackblitz.com/edit/angular-custom-validators-in-dynamic-formarray

app.component.ts

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, Validators, AbstractControl } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  public userForm: FormGroup;

  constructor(private _fb: FormBuilder) {
    this.userForm = this._fb.group({
      firstName: [],
      lastName: [],
      address: this._fb.array([this.addAddressGroup()])
    });
  }

  private addAddressGroup(): FormGroup {
    return this._fb.group({
      street: [],
      city: [],
      state: ['', this.stateValidator],
      isMandatory: [false, [Validators.required]]
    });
  }

  get addressArray(): FormArray {
    return <FormArray>this.userForm.get('address');
  }

  addAddress(): void {
    this.addressArray.push(this.addAddressGroup());
  }

  removeAddress(index: number): void {
    this.addressArray.removeAt(index);
  }

  stateValidator(control: AbstractControl): any {
        if(typeof control === 'undefined' || control === null 
        || typeof control.value === 'undefined' || control.value === null) {
            return {
                required: true
            }
        }

        const stateName: string = control.value.trim();
        const isPrimaryControl: AbstractControl = control.root.get('isMandatory');

        console.log(isPrimaryControl)

        if(typeof isPrimaryControl === 'undefined' || isPrimaryControl === null||
        typeof isPrimaryControl.value === 'undefined' || isPrimaryControl.value === null) {
            return {
                invalidFlag: true
            }
        }

        const isPrimary: boolean = isPrimaryControl.value;

        if(isPrimary === true) {
            if(stateName.length < 3) {
                return {
                    minLength: true
                };
            } else if(stateName.length > 50) {
                return {
                    maxLength: true
                };
            }
        } else {
            control.setValue('');
        }

        return null;
    }
}

app.component.html

<form class="example-form" [formGroup]="userForm">
  <div>
    <mat-card class="example-card">
      <mat-card-header>
        <mat-card-title>Users Creation</mat-card-title>
      </mat-card-header>
      <mat-card-content>
        <div class="primary-container">
          <mat-form-field>
            <input matInput placeholder="First Name" value="" formControlName="firstName">
          </mat-form-field>
          <mat-form-field>
            <input matInput placeholder="Last Name" value="" formControlName="lastName">
          </mat-form-field>
        </div>
        <div formArrayName="address">
          <div class="address-container" *ngFor="let group of addressArray.controls; let i = index;"
            [formGroupName]="i">
            <fieldset>
              <legend>
                <h3>Address: {{i + 1}}</h3>
              </legend>
              <mat-checkbox formControlName="isMandatory">Mandatory</mat-checkbox>
              <div>
                <mat-form-field>
                  <input matInput placeholder="Street" value="" formControlName="street">
                </mat-form-field>
                <mat-form-field>
                  <input matInput placeholder="City" value="" formControlName="city">
                </mat-form-field>
                <mat-form-field>
                  <input matInput placeholder="State" value="" formControlName="state">
                </mat-form-field>
              </div>
            </fieldset>
          </div>
        </div>
        <div class="form-row org-desc-parent-margin">
          <button mat-raised-button (click)="addAddress()">Add more address</button>
        </div>
      </mat-card-content>
    </mat-card>
  </div>
</form>
<mat-card class="pre-code">
  <mat-card-header>
    <mat-card-title>Users Information</mat-card-title>
  </mat-card-header>
  <mat-card-content>
    <pre>{{userForm.value | json}}</pre>
  </mat-card-content>
</mat-card>

请帮助我如何在自定义验证器方法中获取同级抽象控件。

我尝试了以下几个答案中指定的代码

isPrimaryControl = (<FormGroup>control.parent).get('isMandatory')

它抛出了一个错误ERROR Error: too much recursion。请帮助我解决这个问题。

【问题讨论】:

  • 如果您必须放置包含多个 formControls 的验证,请考虑将 Validator 添加到 formGroup 而不是单个 formControl。
  • @SachinGupta - 我这个问题的主要目的是如何让兄弟控制另一个控件。
  • 如我的回答中所述,您可以使用(&lt;FormGroup&gt;control.parent).get('isMandatory')。但是,根据您访问control.parent 的位置,该值可能是undefined,因此您必须进行适当的检查
  • 如果我添加代码isPrimaryControl = (&lt;FormGroup&gt;control.parent).get('isMandatory'),则会收到错误ERROR Error: too much recursion
  • 评论control.setValue('')

标签: javascript angular angular-reactive-forms angular-abstract-control angular-custom-validators


【解决方案1】:

您可能需要将父级转换为FormGroup,尝试使用:

if(control.parent) {
    (<FormGroup>control.parent).get('isMandatory')
}

【讨论】:

  • 它给出了一个控制台错误ERROR Error: control.parent is undefined
  • 我在 chrome 控制台中尝试使用 stateValidator 函数中的调试器,它给了父组,我也能够获得 isMandatory 控件。
  • 能否请您查看StackBlitz中的代码stackblitz.com/edit/…
  • 现在看到了。创建控件时,它没有附加到父级,因此您将收到错误消息。只需勾选if (control.parent),其他一切都应该可以正常工作。
  • 分叉了你的代码stackblitz.com/edit/… 你需要评论control.setValue('') 否则你将无法控制输入任何内容。为了正确验证,可能需要对单击复选框进行一些小的调整。
【解决方案2】:

您可以像这样从表单控件中获取isMandatory 的值,我已将您的stateValidator 方法更改为基本上将control 类型转换为具体子类,然后从controls 数组中您可以获得@987654326 @

stateValidator(control: AbstractControl): any {
let mandatory:boolean=false;
if(control.parent){
  console.log('control',<FormGroup>control.parent.controls.isMandatory.value);
  mandatory=<FormGroup>control.parent.controls.isMandatory.value;
}
    if((typeof control === 'undefined' || control === null 
    || typeof control.value === 'undefined' || control.value === null)&& mandatory) {
      debugger;
        return {
            required: true
        }
    }

    const stateName: string = control.value.trim();
    let isPrimaryControl: AbstractControl=null;
    if(control.parent){
     isPrimaryControl=<FormGroup>control.parent.controls.isMandatory;
    console.log(isPrimaryControl)
    }
    if(typeof isPrimaryControl === 'undefined' || isPrimaryControl === null||typeof isPrimaryControl.value === 'undefined' || isPrimaryControl.value === null) {
        return {
            invalidFlag: true
        }
    }

    const isPrimary: boolean = isPrimaryControl.value;

    if(isPrimary === true) {
        if(stateName.length < 3) {
            return {
                minLength: true
            };
        } else if(stateName.length > 50) {
            return {
                maxLength: true
            };
        }
    } else {
        control.setValue('');
    }

    return null;
}

【讨论】:

  • 我认为如果我使用control.parent.controls 会导致页面崩溃(即在实际应用中它会引发异常)
  • 它抛出了什么异常?
  • 在下面的 StackBlitz stackblitz.com/edit/… 中尝试您的代码,它会使窗口崩溃。
  • 我收到错误ERROR Error: too much recursion
猜你喜欢
  • 1970-01-01
  • 2020-01-13
  • 2022-01-02
  • 2020-03-06
  • 1970-01-01
  • 2018-03-02
  • 2021-11-01
  • 2018-08-05
  • 2019-07-09
相关资源
最近更新 更多