FormGroup异步验证器无法正常工作

时间:2018-06-16 11:50:33

标签: angular validation angular-reactive-forms

我无法弄清楚为什么我的异步验证器无法与 FormGroup 一起正常工作。 我有:模特课

address.model.ts

export interface Address {
  city: string;
  street: string;
}

具有表单和预定义地址的组件

some.component.ts

addressForm: FormGroup;
addresses: Address[] = [
        {city: 'LA', street: 'Pushkina'},
        {city: 'NY', street: 'Shmidta'}
      ];

...

ngOnInit() {
this.addressForm = this.formBuilder.group({
      address: new FormGroup({
        city: new FormControl('', Validators.required),
        street: new FormControl('', Validators.required)
      }, null, this.availableDeliveryAddresses.bind(this))});
}

此组件中定义的异步验证器

availableDeliveryAddresses(formGroup: FormGroup): Promise<any> | Observable<any> {
    const promise = new Promise<any>((resolve) => {
      setTimeout(() => {
        if (this.addresses.indexOf({city: formGroup.controls['city'].value, street: formGroup.controls['street'].value}) === -1)  {
          resolve({'noAddress': true});
        } else {
          resolve(null);
        }
      }, 1500);
    });
    return promise;
  }

在模板中我有

some.component.html

    <div>
              <label for="city">City</label>
              <small *ngIf="!addressForm.get('address.city').valid && addressForm.get('address.city').touched">
                City is required
              </small>
              <small *ngIf="addressForm.get('address.city').touched &&
              addressForm.get('address.street').touched &&
   addressForm.hasError('noAddress', ['address'])">Given address is not our delivery scope</small>
              <input class="form-control" type="text" id="city" formControlName="city">
    </div>

在每种情况下,我收到&#34;鉴于地址不是我们的交付范围&#34;消息。

1 个答案:

答案 0 :(得分:0)

谢谢,问题在于比较对象。 通过===比较对象而不是比较每个属性。