首页 > 解决方案 > 使用反应式表单在 Angular 中检查后,表达式发生了变化

问题描述

我在 Angular 6 中做一个 Web 应用程序,我正在使用 Reactive Forms。我有一个带有数组的表单组,我将值设置在ngOnInit. 我有一个自定义验证器来知道调用的字段id是否是唯一的。

officesFormGroup: FormGroup;

constructor(private fb: FormBuilder) {
    this.officesFormGroup = this.fb.group({
      offices: this.fb.array([], Validators.required)
    });
  }

ngOnInit() {
      this.setOffices();
  }

setOffices() {
    const control = this.officesForm;

    this.company.offices.forEach((office, index) => {
      control.push(this.fb.group({
        id: office.id,
        name: office.name,
        address: office.address,
        services: this.fb.array([], Validators.required)
      }, {validator: this.officeValidator.bind(this)}));
  }

officeValidator(control: AbstractControl) {
    const id = control.get('id').value;

    if (id !== null && id !== '') {
      const offices: Office[] = this.officesForm.value;

      const isIdUnique = offices.map(office => office.id)
        .some(value => value === id);

      if (isIdUnique) {
        control.get('id').setErrors({unavailable: true});
      } else {
        control.get('id').setErrors(null);
      }
    }
  }

get officesForm() {
    return this.officesFormGroup.get('offices') as FormArray;
  }

要将新办公室添加到阵列:

addOffice() {
    const office = this.fb.group({
      id: [null, Validators.required],
      name: [null, Validators.required],
      address: [null, Validators.required],
      services: this.fb.array([], Validators.required)
    }, {validator: this.officeValidator.bind(this)});

    this.officesForm.push(office);
  }

ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改。以前的值:'ngIf: false'。当前值:'ngIf: true'。

第一次加载页面时,调用的字段id显示为红色,好像有错误,这是错误的。id如果用户添加另一个办公室并在该字段中写了一些东西,它应该检查唯一性。

My goal is, if the user adds a new office or try to edit the id of an existing office, check if the id is unique, I mean, if no other office has the same id.

标签: angular

解决方案


I have used in my application unique validator of @rxweb/reactive-form-validators to check whether Id is unique by using RxwebValidators.unique() in my formControl instance, because at a certain level i was facing the same issue.

I have applied the unique validator on Id property. See the below code

Component.ts :

export class UniqueValidatorComponent implements OnInit {


officesFormGroup: FormGroup;

constructor(private fb: FormBuilder) {
    this.officesFormGroup = this.fb.group({
      offices: this.fb.array([])
    });
  }

ngOnInit() {

  this.addOffice();

  }
addOffice() {
    const office = this.fb.group({
      id: [null,[ Validators.required,RxwebValidators.unique()]],
      name: [null, Validators.required],
      address: [null, Validators.required],
      services: this.fb.array([], Validators.required,)
    });
     this.officesForm.push(office);
  }
get officesForm() {
    return this.officesFormGroup.get('offices') as FormArray;
  }


}

Please refer this example : Stackblitz

Refer this Question related to unique validation


推荐阅读