prabhat gundepalli
prabhat gundepalli

Reputation: 967

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>

Upvotes: 1

Views: 3150

Answers (1)

Alexander Staroselsky
Alexander Staroselsky

Reputation: 38767

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!

Upvotes: 5

Related Questions