angular - 最小\最大形式输入验证器角度
问题描述
我尝试将年份输入限制为 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;
解决方案
你可以这样做:添加一个事件并在那里进行计算。您可以使用模糊事件
// 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 事件,它会很好地工作!
推荐阅读
- c# - Azure 上的 Blazor 中的 HttpClient.GetJsonAsync() 导致“无效的 JSON 字符串”,在本地它工作得很好。知道为什么吗?
- c - 什么代码更耗费 CPU:while(*p) 或 while(i--)?
- java - 在 Mac os high sierra 上安装 netbeans 8.2 / 在 mac os high sierra 上安装 netbeans 8.2
- git - 为什么我不能通过 SSH 克隆 Azure Dev Ops 存储库?
- python - 使用全局范围变量的最佳实践?
- asp.net-core - ASP.Net Core appsetting.json 数据库连接理解
- git - Git 镜像在目标存储库上创建了不需要的 PR 引用
- python - 如何将 range(5) 中的值分配给变量?
- sql - Presto SQL 得到 yyyymm 减去 2 个月
- r - 将多个 csv 文件读入单个 df 并将数字迭代器作为列添加到 df