0

我有heroForm其中包含表单数组entities。每一项都是FormGroup

这是示例:

this.heroForm = this.fb.group({
      entities: this.fb.array([]),
    });

这是我向数组添加新组的方式:

  addEntity() {
    this.entities.push(this.createFormGroup(new Address()));
  }

这是我创建单个组的方式:

  createFormGroup(address: Address) {
    return this.fb.group({
      'street': new FormControl(address.street, []),
      'city': new FormControl(address.city, [duplicateCity]),
      'state': new FormControl(address.state, []),
      'zip': new FormControl(address.zip, [])
    });
  }

这是自定义验证功能:

function duplicateCity(input: FormControl): any {
  if (!input.root || !(<FormGroup>input.root).controls) {
    return null;
  }

  // Do some validation.
  input.value === ...
}

现在我想遍历City槽控件并比较它们的值。如果我发现城市名称出现了两次,我想返回错误。

问题是我不想比较相同的控件,我想跳过它。什么应该是准确的方法来做到这一点?

4

1 回答 1

1

其实我错过了这部分:

function duplicateCity(id: number): any {
  return (control: AbstractControl): { [key: string]: any } => {
    if (!control.root || !(<FormGroup>control.root).controls) {
      return null;
    }

    // Do some logic

  };

函数duplicateCity(id: number)现在是返回验证函数的工厂。我可以ID在创建表单组期间动态传递参数,如下例所示:

createFormGroup(address: Address, id: number) {
    return this.fb.group({
      'street': new FormControl(address.street, []),
      'city': new FormControl(address.city, [duplicateCity(id)]),
      'state': new FormControl(address.state, []),
      'zip': new FormControl(address.zip, [])
    });
于 2017-10-26T17:28:49.830 回答