Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activate angular validators only if input is visible

I'm trying to get this to work but I don't know how, I have several inputs that are only displayed when the user needs them.But if they are activated, it must be necessary to fill them. So i got this

component.ts

    dataForm = new FormControl({
       myInput: new FormControl(null, Validators.required)
    })

component.html

<form [formGroup]="dataForm">
     <input formControlName="myInput" type="number" *ngIf="inputActive">

   <button type="submit" [disabled]="!dataForm.valid">
</form>

The problem I have is that when the inputActive variable is false and the input is not shown, the button is still disabled because the field is empty

And I want that when the input is not shown, its validators are not executed so that the button is enabled

Can anyone help me to achieve this?

like image 247
PacMan Programador Avatar asked Aug 30 '25 17:08

PacMan Programador


1 Answers

What you need to do is disable the control instead of or in addition to removing/hiding the form field. This is done by calling disable() on the control. We will use this together with the related disabled property to achieve the desired effect.

@Component({
  // ...boilerplate 
})
export class MyComponent {
  constructor(readonly formBuilder: FormBuilder) {}

  dataForm = this.formBuilder.group({
    anotherInput: this.formBuilder.control(''), // see note
    myInput: this.formBuilder.control(null, Validators.required)
  });

  disableControl(control: AbstractControl) {
    control.disable();
  }
}

In the template

<form [formGroup]="dataForm">
  <input formControlName="myInput" type="number" 
    [hidden]="dataForm.controls.myInput.disabled">

  <input formControlName="anotherInput">

  <button type="submit" [disabled]="!dataForm.valid">Submit</button>
</form>

<button (click)="disableControl(dataForm.controls.myInput)" type="button"></button>

stackblitz

This also helps use organize the form since we don't have an inputActive property to maintain separately from form state.

Note that the whole form group will be considered disabled if all of its children are disabled.

like image 72
Aluan Haddad Avatar answered Sep 02 '25 12:09

Aluan Haddad