Validated an input that's outside of the ReactiveForms model

Viewed 48

StackBlitz example

I am using an Angular Reactive form that has 3 inputs, each having its own validation. I have an input that is not part of the form - its an input that sits inside its own component where it has its own reactive form.

I am trying to pass on a property of [disabled]="registerForm.invalid" that comes from the make up of the 3 inputs on that view. e.g. if they are all valid "then send value false", if one is invalid "then send value true". This will make the single input either disabled/enabled. [disabled]="true or false" works so I know that the issue is with reading the validity of the form.

I thought registerForm.invalid would send an updated value of true/false on every input change in the reactive form therefore sending the value on that I require.

An option could be to have a ngOnChanges that listens for input changes whether they are valid of not and assign a true/false bool to this.disabled and pass that through to the component. - however, I am sure there is a simpler way here.

HTML

<app-input label="Search" [value]="" [disabled]="registerForm.invalid ? true : false"></app-input>

StackBlitz example

1 Answers

The problem is that the form control in the AppInputComponent is created on ngOnInit. When <app-input would receive a new value, ngOnInit would not be triggered.

You might leverage getter and setter to solve it (Stackblitz):

  @Input('disabled') get disabled() {
    return this.control.disabled;
  } 
  set disabled(value) {
    if (value) {
      this.control?.disable();
    } else {
      this.control?.enable();
    }
  } 

this.control will be null when the initial value would be set for the property. It happens before ngOnInit.

Or ngOnChanges as you mentioned

  ngOnChanges(changes: SimpleChanges) {
    if (changes.disabled) {
      if (changes.disabled.currentValue) {
        this.control.disable();
      } else {
        this.control.enable();
      }
    }
  }
Related