0

我正在FormGroup以下列方式构建我的:

this.datesGroup = this.fb.group({
  arrivalDate: [null, Validators.required],
  departureDate: [null, Validators.required]
}, (fg: FormGroup) => {
  console.log('validate');
  return moment.unix(fg.value.departureDate.epoc).diff(moment.unix(fg.value.arrivalDate.epoc)) > 0 ?
    null : {
      'departureBeforeArrival': true
    };
});
this.formGroup = this.fb.group({
  dates: this.datesGroup,
  accommodation: ['', Validators.required]
});

但是上面的验证箭头函数永远不会被触发;控制台从不记录。我究竟做错了什么?

4

1 回答 1

1

FormBuilder.group方法有 2 个参数:

group(controlsConfig: {
        [key: string]: any;
    }, extra?: {
        [key: string]: any;
    } | null): FormGroup;

哪里extra可以object与财产validator和/或asyncValidator

所以我会将您的代码更改为:

this.datesGroup = this.fb.group({
  arrivalDate: [null, Validators.required],
  departureDate: [null, Validators.required]
}, {
  validator: (fg: FormGroup) => {
    console.log('validate');
    return 1 > 0 ?
      null : {
        'departureBeforeArrival': true
      };
  }
});

现场示例可以在这里找到https://plnkr.co/edit/BcExweMVcVxy1yKhwmJp?p=preview

于 2017-06-20T05:47:43.443 回答