Cross field validation doesn't work in Angular












1















I have two date fields in two separate components. I set validations on the effective date to validate if effective date is earlier than application date. If it's earlier than application date, error message should display.



My problem right now is: if user input application date first, and effective date second, the validation works fine. But if user change the application date after they input the effective date, the validation won't fire. In another word, the validation only fire when effective date change.



How can I make the validation on effective date fire when application date changed? I also noticed that when effectiveDate is earlier than application date, the error message display. Then I change the application date to a valid date, the error message won't go away.



I have tried to pass the application date to the effectiveDate component. However, it doesn't work as I expected.



step1.component.html is the page to call the two components. I pass the applicationDate$ into the child component as [minEffectiveDate]="applicationDate$ | async".



step1.component.html, application date is inside the app-internal-use component.



<app-internal-use formControlName="internalUse" (brokerSearchIDResult)="addBrokerToApp($event)"
(clientSearchIDResult)="handleClientSearchResult($event)" [shouldShowBrokerSearch]="shouldShowCommissionSplitBasedOnRoles">
</app-internal-use>
...
<div class="col-sm-5">
<app-plan-effective-date formControlName="effectiveDate" [submitted]="submitted" [minEffectiveDate]="applicationDate$ | async"></app-plan-effective-date>
</div>


effectiveDate.component.html



<label>Effective Date</label>
<div class="input-group margin-xs-bottom-10" [ngClass]="{ 'has-error' : !this.control.valid && (control.touched || submitted) }">
<input class="form-control" [formControl]="control" bsDatepicker required [minDate]="minEffectiveDate"
#dpEffdate="bsDatepicker">
<span class="input-group-addon datepicker-icon" (click)="dpEffdate.toggle()">
<i class="fa fa-calendar"></i>
</span>
</div>
<div class="errorMessage" *ngIf="control.hasError('dateNotLessThanSpecifiedDate') && (submitted || control.touched)">Effective
date cannot be less than the application date</div>


effectiveDate.component.ts



...
export class PlanEffectiveDateComponent extends AbstractValueAccessor implements OnInit, Validator, OnChanges {
@Input() submitted = false;
@Input() minEffectiveDate: Date;
control: FormControl;

constructor(private validatorService: ValidatorService, private cd: ChangeDetectorRef) {
super();
}

ngOnInit() {
this.initializeForm();
this.handleFormChanges();
}

ngOnChanges(changes: SimpleChanges) {
const minEffectiveDateChange = changes['minEffectiveDate'];

if (!!minEffectiveDateChange && !minEffectiveDateChange.firstChange &&
minEffectiveDateChange.currentValue !== minEffectiveDateChange.previousValue &&
!!this.control) {
this.setEffectiveDateValidator();
}
}

initializeForm() {
this.control = new FormControl('', this.composeEffectiveDateValidator());
}

setEffectiveDateValidator() {
this.control.clearValidators();
this.control.setValidators(this.composeEffectiveDateValidator());
setTimeout(() => this.control.updateValueAndValidity({ emitEvent: false }), 0);
this.cd.detectChanges();
}

composeEffectiveDateValidator(): ValidatorFn {
const maxEffectiveDate = utils.currentMoment().add(6, 'month').toDate();

return Validators.compose(
[
this.validatorService.dateNotGreaterThanSpecifiedDate(maxEffectiveDate),
this.validatorService.dateNotLessThanSpecifiedDate(this.minEffectiveDate)
]
);
}

handleFormChanges() {
this.control.valueChanges.subscribe(value => {
this.value = value;
});
}

writeValue(value) {
if (value) {
this.control.setValue(value, { emitEvent: false });
}
}

validate(control: FormControl) {
return this.control.valid ? null : { planEffectiveDateRequired: true };
}
}


dateNotLessThanSpecifiedDate function:



  dateNotLessThanSpecifiedDate(maxDate: Date) {
return (control: FormControl): { [key: string]: any } => {
if (!!control.value && control.value < maxDate) {
return { 'dateNotLessThanSpecifiedDate': true };
} else {
return null;
}
};
}


Any help will be appreciated!



Thanks!










share|improve this question





























    1















    I have two date fields in two separate components. I set validations on the effective date to validate if effective date is earlier than application date. If it's earlier than application date, error message should display.



    My problem right now is: if user input application date first, and effective date second, the validation works fine. But if user change the application date after they input the effective date, the validation won't fire. In another word, the validation only fire when effective date change.



    How can I make the validation on effective date fire when application date changed? I also noticed that when effectiveDate is earlier than application date, the error message display. Then I change the application date to a valid date, the error message won't go away.



    I have tried to pass the application date to the effectiveDate component. However, it doesn't work as I expected.



    step1.component.html is the page to call the two components. I pass the applicationDate$ into the child component as [minEffectiveDate]="applicationDate$ | async".



    step1.component.html, application date is inside the app-internal-use component.



    <app-internal-use formControlName="internalUse" (brokerSearchIDResult)="addBrokerToApp($event)"
    (clientSearchIDResult)="handleClientSearchResult($event)" [shouldShowBrokerSearch]="shouldShowCommissionSplitBasedOnRoles">
    </app-internal-use>
    ...
    <div class="col-sm-5">
    <app-plan-effective-date formControlName="effectiveDate" [submitted]="submitted" [minEffectiveDate]="applicationDate$ | async"></app-plan-effective-date>
    </div>


    effectiveDate.component.html



    <label>Effective Date</label>
    <div class="input-group margin-xs-bottom-10" [ngClass]="{ 'has-error' : !this.control.valid && (control.touched || submitted) }">
    <input class="form-control" [formControl]="control" bsDatepicker required [minDate]="minEffectiveDate"
    #dpEffdate="bsDatepicker">
    <span class="input-group-addon datepicker-icon" (click)="dpEffdate.toggle()">
    <i class="fa fa-calendar"></i>
    </span>
    </div>
    <div class="errorMessage" *ngIf="control.hasError('dateNotLessThanSpecifiedDate') && (submitted || control.touched)">Effective
    date cannot be less than the application date</div>


    effectiveDate.component.ts



    ...
    export class PlanEffectiveDateComponent extends AbstractValueAccessor implements OnInit, Validator, OnChanges {
    @Input() submitted = false;
    @Input() minEffectiveDate: Date;
    control: FormControl;

    constructor(private validatorService: ValidatorService, private cd: ChangeDetectorRef) {
    super();
    }

    ngOnInit() {
    this.initializeForm();
    this.handleFormChanges();
    }

    ngOnChanges(changes: SimpleChanges) {
    const minEffectiveDateChange = changes['minEffectiveDate'];

    if (!!minEffectiveDateChange && !minEffectiveDateChange.firstChange &&
    minEffectiveDateChange.currentValue !== minEffectiveDateChange.previousValue &&
    !!this.control) {
    this.setEffectiveDateValidator();
    }
    }

    initializeForm() {
    this.control = new FormControl('', this.composeEffectiveDateValidator());
    }

    setEffectiveDateValidator() {
    this.control.clearValidators();
    this.control.setValidators(this.composeEffectiveDateValidator());
    setTimeout(() => this.control.updateValueAndValidity({ emitEvent: false }), 0);
    this.cd.detectChanges();
    }

    composeEffectiveDateValidator(): ValidatorFn {
    const maxEffectiveDate = utils.currentMoment().add(6, 'month').toDate();

    return Validators.compose(
    [
    this.validatorService.dateNotGreaterThanSpecifiedDate(maxEffectiveDate),
    this.validatorService.dateNotLessThanSpecifiedDate(this.minEffectiveDate)
    ]
    );
    }

    handleFormChanges() {
    this.control.valueChanges.subscribe(value => {
    this.value = value;
    });
    }

    writeValue(value) {
    if (value) {
    this.control.setValue(value, { emitEvent: false });
    }
    }

    validate(control: FormControl) {
    return this.control.valid ? null : { planEffectiveDateRequired: true };
    }
    }


    dateNotLessThanSpecifiedDate function:



      dateNotLessThanSpecifiedDate(maxDate: Date) {
    return (control: FormControl): { [key: string]: any } => {
    if (!!control.value && control.value < maxDate) {
    return { 'dateNotLessThanSpecifiedDate': true };
    } else {
    return null;
    }
    };
    }


    Any help will be appreciated!



    Thanks!










    share|improve this question



























      1












      1








      1


      1






      I have two date fields in two separate components. I set validations on the effective date to validate if effective date is earlier than application date. If it's earlier than application date, error message should display.



      My problem right now is: if user input application date first, and effective date second, the validation works fine. But if user change the application date after they input the effective date, the validation won't fire. In another word, the validation only fire when effective date change.



      How can I make the validation on effective date fire when application date changed? I also noticed that when effectiveDate is earlier than application date, the error message display. Then I change the application date to a valid date, the error message won't go away.



      I have tried to pass the application date to the effectiveDate component. However, it doesn't work as I expected.



      step1.component.html is the page to call the two components. I pass the applicationDate$ into the child component as [minEffectiveDate]="applicationDate$ | async".



      step1.component.html, application date is inside the app-internal-use component.



      <app-internal-use formControlName="internalUse" (brokerSearchIDResult)="addBrokerToApp($event)"
      (clientSearchIDResult)="handleClientSearchResult($event)" [shouldShowBrokerSearch]="shouldShowCommissionSplitBasedOnRoles">
      </app-internal-use>
      ...
      <div class="col-sm-5">
      <app-plan-effective-date formControlName="effectiveDate" [submitted]="submitted" [minEffectiveDate]="applicationDate$ | async"></app-plan-effective-date>
      </div>


      effectiveDate.component.html



      <label>Effective Date</label>
      <div class="input-group margin-xs-bottom-10" [ngClass]="{ 'has-error' : !this.control.valid && (control.touched || submitted) }">
      <input class="form-control" [formControl]="control" bsDatepicker required [minDate]="minEffectiveDate"
      #dpEffdate="bsDatepicker">
      <span class="input-group-addon datepicker-icon" (click)="dpEffdate.toggle()">
      <i class="fa fa-calendar"></i>
      </span>
      </div>
      <div class="errorMessage" *ngIf="control.hasError('dateNotLessThanSpecifiedDate') && (submitted || control.touched)">Effective
      date cannot be less than the application date</div>


      effectiveDate.component.ts



      ...
      export class PlanEffectiveDateComponent extends AbstractValueAccessor implements OnInit, Validator, OnChanges {
      @Input() submitted = false;
      @Input() minEffectiveDate: Date;
      control: FormControl;

      constructor(private validatorService: ValidatorService, private cd: ChangeDetectorRef) {
      super();
      }

      ngOnInit() {
      this.initializeForm();
      this.handleFormChanges();
      }

      ngOnChanges(changes: SimpleChanges) {
      const minEffectiveDateChange = changes['minEffectiveDate'];

      if (!!minEffectiveDateChange && !minEffectiveDateChange.firstChange &&
      minEffectiveDateChange.currentValue !== minEffectiveDateChange.previousValue &&
      !!this.control) {
      this.setEffectiveDateValidator();
      }
      }

      initializeForm() {
      this.control = new FormControl('', this.composeEffectiveDateValidator());
      }

      setEffectiveDateValidator() {
      this.control.clearValidators();
      this.control.setValidators(this.composeEffectiveDateValidator());
      setTimeout(() => this.control.updateValueAndValidity({ emitEvent: false }), 0);
      this.cd.detectChanges();
      }

      composeEffectiveDateValidator(): ValidatorFn {
      const maxEffectiveDate = utils.currentMoment().add(6, 'month').toDate();

      return Validators.compose(
      [
      this.validatorService.dateNotGreaterThanSpecifiedDate(maxEffectiveDate),
      this.validatorService.dateNotLessThanSpecifiedDate(this.minEffectiveDate)
      ]
      );
      }

      handleFormChanges() {
      this.control.valueChanges.subscribe(value => {
      this.value = value;
      });
      }

      writeValue(value) {
      if (value) {
      this.control.setValue(value, { emitEvent: false });
      }
      }

      validate(control: FormControl) {
      return this.control.valid ? null : { planEffectiveDateRequired: true };
      }
      }


      dateNotLessThanSpecifiedDate function:



        dateNotLessThanSpecifiedDate(maxDate: Date) {
      return (control: FormControl): { [key: string]: any } => {
      if (!!control.value && control.value < maxDate) {
      return { 'dateNotLessThanSpecifiedDate': true };
      } else {
      return null;
      }
      };
      }


      Any help will be appreciated!



      Thanks!










      share|improve this question
















      I have two date fields in two separate components. I set validations on the effective date to validate if effective date is earlier than application date. If it's earlier than application date, error message should display.



      My problem right now is: if user input application date first, and effective date second, the validation works fine. But if user change the application date after they input the effective date, the validation won't fire. In another word, the validation only fire when effective date change.



      How can I make the validation on effective date fire when application date changed? I also noticed that when effectiveDate is earlier than application date, the error message display. Then I change the application date to a valid date, the error message won't go away.



      I have tried to pass the application date to the effectiveDate component. However, it doesn't work as I expected.



      step1.component.html is the page to call the two components. I pass the applicationDate$ into the child component as [minEffectiveDate]="applicationDate$ | async".



      step1.component.html, application date is inside the app-internal-use component.



      <app-internal-use formControlName="internalUse" (brokerSearchIDResult)="addBrokerToApp($event)"
      (clientSearchIDResult)="handleClientSearchResult($event)" [shouldShowBrokerSearch]="shouldShowCommissionSplitBasedOnRoles">
      </app-internal-use>
      ...
      <div class="col-sm-5">
      <app-plan-effective-date formControlName="effectiveDate" [submitted]="submitted" [minEffectiveDate]="applicationDate$ | async"></app-plan-effective-date>
      </div>


      effectiveDate.component.html



      <label>Effective Date</label>
      <div class="input-group margin-xs-bottom-10" [ngClass]="{ 'has-error' : !this.control.valid && (control.touched || submitted) }">
      <input class="form-control" [formControl]="control" bsDatepicker required [minDate]="minEffectiveDate"
      #dpEffdate="bsDatepicker">
      <span class="input-group-addon datepicker-icon" (click)="dpEffdate.toggle()">
      <i class="fa fa-calendar"></i>
      </span>
      </div>
      <div class="errorMessage" *ngIf="control.hasError('dateNotLessThanSpecifiedDate') && (submitted || control.touched)">Effective
      date cannot be less than the application date</div>


      effectiveDate.component.ts



      ...
      export class PlanEffectiveDateComponent extends AbstractValueAccessor implements OnInit, Validator, OnChanges {
      @Input() submitted = false;
      @Input() minEffectiveDate: Date;
      control: FormControl;

      constructor(private validatorService: ValidatorService, private cd: ChangeDetectorRef) {
      super();
      }

      ngOnInit() {
      this.initializeForm();
      this.handleFormChanges();
      }

      ngOnChanges(changes: SimpleChanges) {
      const minEffectiveDateChange = changes['minEffectiveDate'];

      if (!!minEffectiveDateChange && !minEffectiveDateChange.firstChange &&
      minEffectiveDateChange.currentValue !== minEffectiveDateChange.previousValue &&
      !!this.control) {
      this.setEffectiveDateValidator();
      }
      }

      initializeForm() {
      this.control = new FormControl('', this.composeEffectiveDateValidator());
      }

      setEffectiveDateValidator() {
      this.control.clearValidators();
      this.control.setValidators(this.composeEffectiveDateValidator());
      setTimeout(() => this.control.updateValueAndValidity({ emitEvent: false }), 0);
      this.cd.detectChanges();
      }

      composeEffectiveDateValidator(): ValidatorFn {
      const maxEffectiveDate = utils.currentMoment().add(6, 'month').toDate();

      return Validators.compose(
      [
      this.validatorService.dateNotGreaterThanSpecifiedDate(maxEffectiveDate),
      this.validatorService.dateNotLessThanSpecifiedDate(this.minEffectiveDate)
      ]
      );
      }

      handleFormChanges() {
      this.control.valueChanges.subscribe(value => {
      this.value = value;
      });
      }

      writeValue(value) {
      if (value) {
      this.control.setValue(value, { emitEvent: false });
      }
      }

      validate(control: FormControl) {
      return this.control.valid ? null : { planEffectiveDateRequired: true };
      }
      }


      dateNotLessThanSpecifiedDate function:



        dateNotLessThanSpecifiedDate(maxDate: Date) {
      return (control: FormControl): { [key: string]: any } => {
      if (!!control.value && control.value < maxDate) {
      return { 'dateNotLessThanSpecifiedDate': true };
      } else {
      return null;
      }
      };
      }


      Any help will be appreciated!



      Thanks!







      javascript angular validation angular-validation angular-validator






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 15 '18 at 15:23







      Julie C.

















      asked Nov 15 '18 at 2:16









      Julie C.Julie C.

      121211




      121211
























          1 Answer
          1






          active

          oldest

          votes


















          0














          We figured this out by using ChangeDetectionStragegy.OnPush. Here is the solution.



          plan-effective-date.component.ts



          control = new FormControl('', this.buildValidator.bind(this));

          constructor(
          private cd: ChangeDetectorRef,
          private controlDir: NgControl,
          ) {
          super();
          this.controlDir.valueAccessor = this;
          }

          ngOnInit() {
          this.handleFormChanges();
          this.controlDir.control.setValidators(this.validate.bind(this));
          this.updateValidity();
          }

          updateValidity() {
          setTimeout(() => {
          this.control.updateValueAndValidity();
          this.controlDir.control.setValidators(this.validate.bind(this));
          this.cd.detectChanges();
          }, 0);
          }


          Inside the ngOnChanges, call the updateValidity()



          ngOnChanges(changes: SimpleChanges) {
          const minEffectiveDateChange = changes['minEffectiveDate'];
          const currentPlanEndDateChange = changes['currentPlanEndDate'];

          if ((!!minEffectiveDateChange && !minEffectiveDateChange.firstChange &&
          minEffectiveDateChange.currentValue !== minEffectiveDateChange.previousValue &&
          !!this.control) ||
          (!!this.currentPlanEndDate && !currentPlanEndDateChange.firstChange &&
          currentPlanEndDateChange.currentValue !== currentPlanEndDateChange.previousValue
          && !!this.control)) {
          this.updateValidity();
          }
          }


          buildValidator() method is just to set your customized validators.



          Hope this will help someone who has similar issue with me :)






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53311482%2fcross-field-validation-doesnt-work-in-angular%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            We figured this out by using ChangeDetectionStragegy.OnPush. Here is the solution.



            plan-effective-date.component.ts



            control = new FormControl('', this.buildValidator.bind(this));

            constructor(
            private cd: ChangeDetectorRef,
            private controlDir: NgControl,
            ) {
            super();
            this.controlDir.valueAccessor = this;
            }

            ngOnInit() {
            this.handleFormChanges();
            this.controlDir.control.setValidators(this.validate.bind(this));
            this.updateValidity();
            }

            updateValidity() {
            setTimeout(() => {
            this.control.updateValueAndValidity();
            this.controlDir.control.setValidators(this.validate.bind(this));
            this.cd.detectChanges();
            }, 0);
            }


            Inside the ngOnChanges, call the updateValidity()



            ngOnChanges(changes: SimpleChanges) {
            const minEffectiveDateChange = changes['minEffectiveDate'];
            const currentPlanEndDateChange = changes['currentPlanEndDate'];

            if ((!!minEffectiveDateChange && !minEffectiveDateChange.firstChange &&
            minEffectiveDateChange.currentValue !== minEffectiveDateChange.previousValue &&
            !!this.control) ||
            (!!this.currentPlanEndDate && !currentPlanEndDateChange.firstChange &&
            currentPlanEndDateChange.currentValue !== currentPlanEndDateChange.previousValue
            && !!this.control)) {
            this.updateValidity();
            }
            }


            buildValidator() method is just to set your customized validators.



            Hope this will help someone who has similar issue with me :)






            share|improve this answer




























              0














              We figured this out by using ChangeDetectionStragegy.OnPush. Here is the solution.



              plan-effective-date.component.ts



              control = new FormControl('', this.buildValidator.bind(this));

              constructor(
              private cd: ChangeDetectorRef,
              private controlDir: NgControl,
              ) {
              super();
              this.controlDir.valueAccessor = this;
              }

              ngOnInit() {
              this.handleFormChanges();
              this.controlDir.control.setValidators(this.validate.bind(this));
              this.updateValidity();
              }

              updateValidity() {
              setTimeout(() => {
              this.control.updateValueAndValidity();
              this.controlDir.control.setValidators(this.validate.bind(this));
              this.cd.detectChanges();
              }, 0);
              }


              Inside the ngOnChanges, call the updateValidity()



              ngOnChanges(changes: SimpleChanges) {
              const minEffectiveDateChange = changes['minEffectiveDate'];
              const currentPlanEndDateChange = changes['currentPlanEndDate'];

              if ((!!minEffectiveDateChange && !minEffectiveDateChange.firstChange &&
              minEffectiveDateChange.currentValue !== minEffectiveDateChange.previousValue &&
              !!this.control) ||
              (!!this.currentPlanEndDate && !currentPlanEndDateChange.firstChange &&
              currentPlanEndDateChange.currentValue !== currentPlanEndDateChange.previousValue
              && !!this.control)) {
              this.updateValidity();
              }
              }


              buildValidator() method is just to set your customized validators.



              Hope this will help someone who has similar issue with me :)






              share|improve this answer


























                0












                0








                0







                We figured this out by using ChangeDetectionStragegy.OnPush. Here is the solution.



                plan-effective-date.component.ts



                control = new FormControl('', this.buildValidator.bind(this));

                constructor(
                private cd: ChangeDetectorRef,
                private controlDir: NgControl,
                ) {
                super();
                this.controlDir.valueAccessor = this;
                }

                ngOnInit() {
                this.handleFormChanges();
                this.controlDir.control.setValidators(this.validate.bind(this));
                this.updateValidity();
                }

                updateValidity() {
                setTimeout(() => {
                this.control.updateValueAndValidity();
                this.controlDir.control.setValidators(this.validate.bind(this));
                this.cd.detectChanges();
                }, 0);
                }


                Inside the ngOnChanges, call the updateValidity()



                ngOnChanges(changes: SimpleChanges) {
                const minEffectiveDateChange = changes['minEffectiveDate'];
                const currentPlanEndDateChange = changes['currentPlanEndDate'];

                if ((!!minEffectiveDateChange && !minEffectiveDateChange.firstChange &&
                minEffectiveDateChange.currentValue !== minEffectiveDateChange.previousValue &&
                !!this.control) ||
                (!!this.currentPlanEndDate && !currentPlanEndDateChange.firstChange &&
                currentPlanEndDateChange.currentValue !== currentPlanEndDateChange.previousValue
                && !!this.control)) {
                this.updateValidity();
                }
                }


                buildValidator() method is just to set your customized validators.



                Hope this will help someone who has similar issue with me :)






                share|improve this answer













                We figured this out by using ChangeDetectionStragegy.OnPush. Here is the solution.



                plan-effective-date.component.ts



                control = new FormControl('', this.buildValidator.bind(this));

                constructor(
                private cd: ChangeDetectorRef,
                private controlDir: NgControl,
                ) {
                super();
                this.controlDir.valueAccessor = this;
                }

                ngOnInit() {
                this.handleFormChanges();
                this.controlDir.control.setValidators(this.validate.bind(this));
                this.updateValidity();
                }

                updateValidity() {
                setTimeout(() => {
                this.control.updateValueAndValidity();
                this.controlDir.control.setValidators(this.validate.bind(this));
                this.cd.detectChanges();
                }, 0);
                }


                Inside the ngOnChanges, call the updateValidity()



                ngOnChanges(changes: SimpleChanges) {
                const minEffectiveDateChange = changes['minEffectiveDate'];
                const currentPlanEndDateChange = changes['currentPlanEndDate'];

                if ((!!minEffectiveDateChange && !minEffectiveDateChange.firstChange &&
                minEffectiveDateChange.currentValue !== minEffectiveDateChange.previousValue &&
                !!this.control) ||
                (!!this.currentPlanEndDate && !currentPlanEndDateChange.firstChange &&
                currentPlanEndDateChange.currentValue !== currentPlanEndDateChange.previousValue
                && !!this.control)) {
                this.updateValidity();
                }
                }


                buildValidator() method is just to set your customized validators.



                Hope this will help someone who has similar issue with me :)







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 26 '18 at 16:27









                Julie C.Julie C.

                121211




                121211
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53311482%2fcross-field-validation-doesnt-work-in-angular%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Bressuire

                    Vorschmack

                    Quarantine