Getting Angular FormControl Validators.max() value

Viewed 29

I´m making a component which takes a FormControl as an input.

In this component, i´d like to disable a button if the formControls value equals the Validator.max() value.

this.formC = this.fb.control( // formcontrol created in the parent component
   maxValue,
     [
        Validators.max(maxValue),
        Validators.min(1),
        Validators.required
     ]);

 <!-- Button used in the child component -->
 <button
    mat-flat-button
    color="accent"
    [disabled]="maxValue" // here I´d like to get the  Validators.max() value
    (click)="increaseQuanity()"
  >+</button>

I could of cause just parse the max value as an @Input(), but I was hoping to find a more elegant way.

1 Answers

You don't disable the button based on a FormControl's value. You disable it based on it's .invalid property.

So your validators take care of Max, as well as Min and Required. If any of those are violated the FormControl becomes .invalid. If the FormControl is part of a FormGroup, that too becomes invalid.

So just just bind disabled to .invalid:

<button
    mat-flat-button
    color="accent"
    [disabled]="formC.invalid" // here I´d like to get the  Validators.max() value
    (click)="increaseQuanity()"
  >+</button>

Hope that helps. If I've missed something, let me know.

Related