角度反应形式和按钮禁用/启用

时间:2019-03-19 14:19:15

标签: angular

我正在使用component.html中的以下代码

<button class="btn btn-primary" [disabled]="!projectForm.valid"
                    (click)="updateProjects()">Update</button>

Component.ts代码在下面

  this.projectForm = this.formBuilder.group({
      Name: new FormControl('', [Validators.required, Validators.pattern('^[a-zA-Z1-9][a-zA-Z1-9, _-]+$')]),
      ProjectID: new FormControl({ value: 'SQ123', disabled: true }),
      ProjectTypeID: new FormControl({ value: null, disabled: true}),
      ProjectSubTypeID: new FormControl({ value: null, disabled: true}),
      LifecycleTemplate: new FormControl('Plan', [Validators.required]),
      ConstructionTypeID: new FormControl({ value: null, disabled: true }, [Validators.required]),
      ContractTypeID: new FormControl({ value: null, disabled: true }, [Validators.required]),
      StartDate: new FormControl('', [Validators.required]),
      StartDateSub: new FormControl('', [Validators.required]),
      EndDate: new FormControl(''),
      EndDateSub: new FormControl(''),
      ProjectAddress: new FormControl({ value: null, disabled: true }, [Validators.required]),
      Description: new FormControl(''),
    });
    this.projectForm.controls['StartDateSub'].valueChanges.subscribe(value => {
      this.validateStartandEndDataSub();
    });
    this.projectForm.controls['EndDateSub'].valueChanges.subscribe(value => {
      this.validateStartandEndDataSub();
    });
由于this.validateStartandEndDataSub();,使用this.validateStartandEndDataSub();功能更新按钮时

无法启用 填写所有值后如何解决错误以启用更新按钮

  validateStartandEndDataSub() {
    const startDate = this.projectFormControls['StartDateSub'].value;
    const endDate = this.projectFormControls['EndDateSub'].value;
    if (endDate) {
      if (startDate > endDate) {
        this.projectFormControls['EndDateSub'].setErrors({ 'incorrect': true });
      } else {
        this.projectFormControls['EndDateSub'].setErrors({'incorrect': false});
      }
    }
  }

1 个答案:

答案 0 :(得分:1)

write a custom validator and add it at the form group level:

export function startBeforeEndValidator(startProp, endProp): ValidatorFn {
  return (control: AbstractControl): {[key: string]: any} | null => {
    const startCtrl = control.get(startProp);
    const endCtrl = control.get(endProp);
    const start = startCtrl ? startCtrl.value : null;
    const end = endCtrl ? endCtrl.value : null;
    return (start && end && start > end) ? {endBeforeStart: true} : null;
  };
}

then just register it like any other validator with your from group and the control properties as arguments.