How to correctly set up Angular2 template-driven form validation for min/max?

147 Views Asked by At

I'm trying to implement a new Angular component with template-driven form validation. I have been following the documentation here, but cannot seem to replicate the results. Specifically, the div showing the error just doesn't appear when the input is invalid.

Here is the source code for context:

Template:

<mat-form-field class="input">
  <input matInput matTooltip="Float value between 0.0 and 1.0"
         type="number"
         placeholder="Confidence"
         min="0.0"
         max="1.0"
         [(ngModel)]="confidence"
         #value="ngModel">
  <mat-error *ngIf="value.invalid &&  (value.errors.min || value.errors.max)">
    Confidence must be an decimal value between 0.0 and 1.0.
  </mat-error>
</mat-form-field>

Relevant component code:

  metadata = {confidence: 0.0, ...};

  get confidence(): number {
    return this.metadata.confidence;
  }

  set confidence(confidenceIn: number) {
    this.metadata.confidence = confidenceIn;
  }

My understanding is that the line #value="ngModel" makes a local variable value containing the value of the input element it was declared on, which then allows me to reference value as in the following *ngIf directive to check for errors.

However, the mat-error element never shows up when the input value is out of range (less than 0, more than 1), so my understanding is probably wrong and/or I've implemented this incorrectly.

Any explanations would be greatly appreciated!

0

There are 0 best solutions below