Angular 6验证数字输入 [英] Angular 6 validate number input
问题描述
我有一个输入,类型是数字.我要设置最小值和最大值,如果输入超出此范围(<最小值或>最大值),将显示错误.
I have an input and the type is number. I want to set min and max, if the input is out of this range (< min or >max), the error will be displayed.
我的问题是,如果输入不为空但无效,则错误消失(例如:min = 10,max = 20,input = 2000,仍然没有错误显示).
My problem is that if the input is not empty but invalid, the error disappears (example: min =10, max =20, input =2000, still no error displays).
我在此站点上搜索,并且有关于验证的帖子,但是解决方案是使用< md-input-container>和< md-error>.我不想使用< md-input-container>和< md-error>.
I search on this site and there is a post about validation but the solution is to use < md-input-container> and < md-error>. I don't want to use < md-input-container> and < md-error>.
参考:此处
总有办法解决我的问题吗?
Is there anyway to solve my problem?
我的add-hero.component.html:
My add-hero.component.html:
<div class="publishedYear">
<label>Publish Year: </label>
<input type="number" id="PublishedYear" name="PublishedYear" required min="10" max="20"
[(ngModel)]="hero.PublishedYear" #publishedYear="ngModel">
<p class="alert alert-danger invalid" *ngIf="publishedYear.errors">Invalid Published Year</p>
</div>
我的Hero.ts
export class Hero {
Id: number;
Name: string;
PublishedYear: number;
Complete?: boolean;
}
推荐答案
感谢您的上述所有回答以及您的努力. 经过几个小时的研究,终于得到了以下答案:
Thanks for all of your answers above and your efforts. After a few hours doing research, I finally got an answer from this : page
如果您有像我这样的问题,这就是答案.
If you have any problem like me, here is the answer.
我的.html文件:
<form [formGroup]="myForm">
<label for="publishedYear">Publish Year: </label>
<input type="number" id="PublishedYear" formControlName="publishedYear">
<div *ngIf="f.publishedYear.errors">
Invalid Published Year
</div>
我的.ts文件:
import { Component, OnInit, Input } from '@angular/core';
import { Hero } from '../Hero';
import { HeroService } from '../hero.service';
import { Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule } from
'@angular/forms';
@Component({
selector: 'app-hero-add',
templateUrl: './hero-add.component.html',
styleUrls: ['./hero-add.component.css']
})
export class HeroAddComponent implements OnInit {
hero: Hero = new Hero();
myForm = new FormGroup({}) // Instantiating our form
get f() { return this.myForm.controls; }
constructor(private heroService: HeroService, private router: Router, private
formBuilder: FormBuilder) {
this.myForm = formBuilder.group({
publishedYear: ['', [Validators.min(1990), Validators.max(2018)]]
});
}
ngOnInit() {
}
}
这篇关于Angular 6验证数字输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!