Search code examples
angularformsmaxlengthangular-reactive-formsangular2-form-validation

How to perform conditional validation in html Angular form


I have a form where I want to implement the MAXLENGTH validation only if the value is not equal to 0.

So if parameter.valueMaxlength === 0 { then dont execute maxlength validation } Is there a way to write this logic in the html file.

 <mat-form-field *ngSwitchCase="'TEXTBOX'" class="example-full-width">
  <input
    matInput
    [placeholder]="parameter.displayName"
    [formControlName]="parameter.id"
    [id]="parameter.id"
    [type]="parameter.dataType"
    [maxlength] = "parameter.valueMaxlength"

  />
</mat-form-field>

Solution

  • Try the following by using a ternary operator with [attr.maxlength]:

    <input
        matInput
        [placeholder]="parameter.displayName"
        [formControlName]="parameter.id"
        [id]="parameter.id"
        [type]="parameter.dataType"
        [attr.maxlength]="parameter.valueMaxlength === 0 ? null : parameter.valueMaxlength" 
    />
    

    maxLength will not render if what's passed is equal to 0, otherwise it will render with a value equal to what's passed in.

    Here is an example in action.

    Hopefully that helps!