首页 > 解决方案 > 最小\最大形式输入验证器角度

问题描述

我尝试将年份输入限制为 0-24,但我所做的一切都没有奏效。有人有想法吗?form.html 中的相关代码:

<mat-card>
    <h1>Add Customer</h1>
    <form #customerForm="ngForm">
        <mat-form-field>
                <input 
                    matInput placeholder="Education years"
                    [(ngModel)] = "years"
                    name = "years"
                    min = "0"
                    max = "24"
                    required="required">
        </mat-form-field>
    </form>
    </mat-card>

form.ts 中的相关代码:

import { Component, OnInit, Input, Output, EventEmitter} from '@angular/core';
import { Customer } from '../interfaces/customer';

@Component({
  selector: 'customerform',
  templateUrl: './customer-form.component.html',
  styleUrls: ['./customer-form.component.css']
})
export class CustomerFormComponent implements OnInit {

  @Input() name: string;
  @Input() years: number;
  @Input() income: number;
  @Input() id: string;

标签: angulartypescriptvalidationmaxmin

解决方案


你可以这样做:添加一个事件并在那里进行计算。您可以使用模糊事件

// In HTML
<mat-card>
    <h1>Add Customer</h1>
    <form #customerForm="ngForm">
        <mat-form-field>
                <input 
                    matInput placeholder="Education years"
                    [(ngModel)] = "years"
                    name = "years"
                    (blur)="blurEvent($event)   // Add this event in HTML
                    required="required">

                // Add a small tag, add styles to make the text color red
                <small *ngIf="blurEventError" style="'color': red">
                     Value should be between 0 and 24
                 </small>

        </mat-form-field>
    </form>
    </mat-card>

// In component.ts file

blurEventError: boolean = false;

blurEvent(event) {
  if (event && event.target.value) {
     if (
         customerForm.controls.years.value < 0 ||
         customerForm.controls.years.value > 24
     ) {
         this.blurEventError = true;
     } 
  }
}

如果这不起作用,您可以添加一个 keypress / keyup / keydown 事件,它会很好地工作!


推荐阅读