我有一个Angular 2项目,有两个输入字段,大于和小于。我想检查以确保用户输入的过滤器之间不会互相矛盾的有效值,并且我希望在前端动态地执行此操作,而无需用户提交表单。
具体来说,我想确保"大于"大于"输入不大于"小于"内的值。领域。
我该怎么办?
<form (submit)="onSubmit()" id="inputForm" class="form-group" class="row">
<h3>Price Filters</h3>
<span>Greater than:</span>
<input type="number" name="greaterThanValue" [(ngModel)]="greaterThanValue" placeholder="0">
<span>Less than:</span>
<input type="number" name="lessThanValue" [(ngModel)]="lessThanValue">
<input type="submit">
</form>
答案 0 :(得分:2)
您可以使用ngModelChange
通知更改
<强> HTML:强>
<input type="number" name="greaterThanValue" [(ngModel)]="greaterThanValue" (ngModelChange)="onChange($event)" placeholder="0">
<span>Less than:</span>
<input type="number" name="lessThanValue" [(ngModel)]="lessThanValue" (ngModelChange)="onChange($event)">
<强> app.ts:强>
public onChange(event: any): void {
if (this.greaterThanValue > this.lessThanValue) {
console.log('Incorrect');
this.greaterThanValue = this.lessThanValue - 1;
}
}
更新:如果您只想显示消息而不是调整值,则可以设置标记并根据标记值显示内容,
<div style="color: red" *ngIf="isInvalid">Please check your ranges</div>
public onChange(event: any): void {
this.isInvalid = this.greaterThanValue > this.lessThanValue;
}