在Angular中,您可以使用FormGroup和FormControl来创建表单并验证输入类型。对于数字输入,可以使用Validators.pattern()来验证输入是否为数字。以下是一个示例代码:
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-form',
template: `
`
})
export class FormComponent {
myForm: FormGroup;
constructor() {
this.myForm = new FormGroup({
'myNumber': new FormControl('', [Validators.pattern('^[0-9]*$')])
});
}
onSubmit() {
if (this.myForm.valid) {
// 处理表单提交
}
}
}
在上面的代码中,我们使用Validators.pattern()将正则表达式'^[0-9]*$'传递给FormControl来验证输入是否为数字。
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { FormComponent } from './form.component';
@NgModule({
imports: [BrowserModule, ReactiveFormsModule],
declarations: [FormComponent],
bootstrap: [FormComponent]
})
export class AppModule { }
以上就是一个简单的Angular表单输入类型为“数字”的例子。通过使用Validators.pattern()验证器,我们可以确保只接受数字输入。
上一篇:Angular测试