Javascript 使用ngModel限制用户输入角度2中最多2位小数的最大5位整数
我有一个包含[ngModel]的输入文本字段,我的要求是允许用户最多只输入5位数字,最多2位小数。创建指令是最好的解决方案,但我不知道如何实现此功能。请帮忙 要求为-99999.99是正确的 99.9也是正确的Javascript 使用ngModel限制用户输入角度2中最多2位小数的最大5位整数,javascript,angular,Javascript,Angular,我有一个包含[ngModel]的输入文本字段,我的要求是允许用户最多只输入5位数字,最多2位小数。创建指令是最好的解决方案,但我不知道如何实现此功能。请帮忙 要求为-99999.99是正确的 99.9也是正确的 我使用了number pipe[ngModel]=cost | number:'1.0-2',但它不起作用。您可以通过两种方式实现这一点。模板驱动的表单和反应式表单。请查找下面的示例,其中给出了验证工作原理的一些想法 在TS文件中:模板驱动的表单 希望对您有所帮助您可以使用的模式属性来验
我使用了number pipe[ngModel]=cost | number:'1.0-2',但它不起作用。您可以通过两种方式实现这一点。模板驱动的表单和反应式表单。请查找下面的示例,其中给出了验证工作原理的一些想法 在TS文件中:模板驱动的表单
希望对您有所帮助您可以使用的模式属性来验证您的输入。我为你的要求添加了一个模式,正/负,0到5位,0到2位小数:
import { Component } from '@angular/core';
@Component({
selector: 'sandboxngforms',
template: `
<h1>Hello World</h1>
<!-- by default html5 has validation. if u add a directive called "novalidate" in form tag
then we can build our customised template.
create an id called f so that we can easily group-->
<!--group the form by value id #f instead of submit> use ngSubmit so that u can use the values used in the form and call the function -->
<form novalidate #f="ngForm" (ngSubmit)="onSubmit(f)">
<div class="form-group">
<label>Name</label>
<input
type="text"
class="form-control"
[(ngModel)]="user.name"
name="name"
#userName="ngModel"
minlength="2"
required>
<!-- using the name input field #tagid (i.e userName) write the below if condition
touched is a special directive that allows u when u click on the field and click outside
will produce error-->
<div *ngIf="userName.errors?.required && userName.touched" class="alert alert-danger">Name is required</div>
<div *ngIf="userName.errors?.minlength && userName.touched"
class="alert alert-danger">Name should be at least 2 characters
</div>
</div>
<div class="form-group">
<label>Email</label>
<input
type="text"
class="form-control"
[(ngModel)]="user.email"
name="email"
#userEmail="ngModel"
required
>
<div *ngIf="userEmail.errors?.required && userEmail.touched" class="alert alert-danger">Email is required</div>
</div>
<div class="form-group">
<label>Phone</label>
<input
type="text"
class="form-control"
[(ngModel)]="user.phone"
name="phone"
#userPhone="ngModel"
minlength="10"
>
<div *ngIf="userPhone.errors?.minlength && userPhone.touched" class="alert alert-danger">Enter a valid phone
number
</div>
</div>
<input type="submit" class="btn btn-success" value="Submit">
</form>
`
})
export class SandboxngformsComponent {
// create an user object
user = {
name: '',
email: '',
phone: ''
}
onSubmit({value, valid}) {
if (valid) {
console.log(value);
} else {
console.log('Form is invalid');
}
}
}