#Control validators not updating when ngOnChanges

5 messages · Page 1 of 1 (latest)

ornate root
#

Hello, guys! I got a control which can either be required or not based on a @Input() property. It's quite simple actually, if value is equal to 22 I do need it to be required, if 21 no validators is necessary. The problem it is not updating and I do not know why. Here's my methods:

*ngOnChanges

  ngOnChanges(changes: SimpleChanges): void {
    this.finalizeBusinessData = changes['finalizeBusinessData'].currentValue;

    if (this.finalizeBusinessData.business && this.finalizeBusinessData.status) {
      this.initFinalizeForm(this.finalizeBusinessData.status);
    }
  }

*my init form method

  initFinalizeForm = (status: number) => {

    console.log(this.finalizeBusinessData);
    
    this.finalizeForm = this.form_builder.group({
      status: [this.finalizeBusinessData.status],
      date: [this.dates_service.today_ptBR, [Validators.required]],
      reason: ['']
    });

    if (this.finalizeForm && this.finalizeForm.controls) {
      const reasonControl = this.finalizeForm.controls['reason'];

      status === 22 ? reasonControl.setValidators([Validators.required]) : reasonControl.setValidators(null);
      reasonControl.updateValueAndValidity();
    }
  }

as you guys can see, I've put a console.log right at the start of the method and I can see my value is coming just as expected. Once I change it in my form's parent and everything goes well, my console.log updates, buy my validation not.

thank you very much for your time!

safe tangle
#

I believe the initFinalizeForm is recreating the FormGroup everytime its called

#

Which means that any form controls previously created (and their validators) are discarded and new ones are created

ornate root
#

any ideia how can I resolve this?

safe tangle
#

Maybe create your form only once in your ngOnInit method, and then in ngOnChanges, just update the validators as needed