为什么我的验证函数来验证在angular 5中未调用的formarray?

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

嗨,我的验证程序遇到问题,因为它没有被调用。

当前,我有一个Angular 5组件,其中定义了formgroupformgroup具有一个表单数组元素。 formgroup数组中的每个元素都是FormGroup类型。我写了一个名为validatorduplicateClientNameValidator。但是,当我编辑表格时,validator没有被调用。所以下面是我的组件ts文件

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormArray, FormControl } from '@angular/forms';
import { duplicateClientNameValidator } from '../../shared';


@Component({
  selector: 'pc-account-service-provider-clients',
  templateUrl: './account-service-provider-clients.component.html',
  styleUrls: ['./account-service-provider-clients.component.scss']
})
export class AccountServiceProviderClientsComponent implements OnInit {

  formGroup: FormGroup;
  constructor( private fb: FormBuilder) { }

  ngOnInit() {
    this.formGroup = this.fb.group({
        aliases: this.fb.array([]) 
       },[duplicateClientNameValidator('aliases')]);
  }

  get aliases() {
    return this.formGroup.get('aliases') as FormArray;
  }

  addAlias() {
    const formGroupNew: FormGroup = new FormGroup( {
          id: new FormControl( { value:'', disabled:false}),
          name: new FormControl({ value:'', disabled:false},[Validators.required, Validators.maxLength(50)]),
          companyNumber: new FormControl({ value:'', disabled:false},Validators.maxLength(20))
      }
    );
    this.aliases.push(formGroupNew);
  }

removeItem( index :number){
    this.aliases.removeAt(index);
}

handleSubmit() {}


get cancelLink(): string {
  return  '/dashboard';
}

}

以下是我的validator功能duplicateClientNameValidator的定义

export function duplicateClientNameValidator( serviceProviderClientControlArrayName: string):ValidationErrors | null {

 return (control: FormGroup): ValidationErrors | null => {

         const aliases:FormArray =  <FormArray>control.get(serviceProviderClientControlArrayName);

         for(const formGrp of aliases.controls ) {
          const frmGroup: FormGroup = <FormGroup> formGrp;
          console.log(frmGroup.get('name').value);
         }
      return null;
  };

}

以下是UI的快照。我可以使用+图标将新项目添加到formgroup中,在编辑完所有字段后,我希望duplicateClientNameValidator被调用。但是它没有被调用。非常感谢您的帮助

enter image description here

angular5 angular-validation reactive-forms
1个回答
0
投票
this.formGroup = this.fb.group({ aliases: this.fb.array([]) },{validator: [duplicateClientNameValidator('aliases')]});
© www.soinside.com 2019 - 2024. All rights reserved.