【问题标题】:Angular 2 - Checking for radio button selection valueAngular 2 - 检查单选按钮选择值
【发布时间】:2019-05-04 02:28:17
【问题描述】:

我正在开发一个应用程序,其中我们有一个带有订单的页面。用户可以输入新订单,也可以从现有订单列表中进行选择,然后根据该选择填充订单表格。我正在尝试根据用户是否已开始为“新”订单输入数据,然后从现有订单中进行选择来实施验证。如果他们已经开始输入数据,我想抛出一个确认对话框,提醒他们他们将覆盖他们已经输入的内容。我试图弄清楚如何在实际更改之前捕获单选按钮选择,看看它们是否从“新”变为“现有”,然后执行一些验证

模板代码:

<mat-radio-group formControlName="orderAction" (change)="onOrderActionBlur($event)">
  <mat-radio-button value="new" >New Order</mat-radio-button>
  <mat-radio-button value="existing">Existing Order</mat-radio-button>
</mat-radio-group>

在控制器中:

onOrderActionBlur($event): any {
   this.orderAction= this.form.get('orderAction').value;

   if (this.orderAction=== 'new') {
     // make sure the fields haven't been changed 
   }
}

我以为我可以使用模糊事件,但是当我选择关闭新时,该值是存在的。可能有更好的方法,因为我是 Angular 新手,所以对建议完全开放。提前致谢。

【问题讨论】:

  • 如果我对您的问题的理解正确,您可以检查form 上的isDirty 属性,看看是否有任何属性已被修改?

标签: angular angular-material


【解决方案1】:

表单控件具有许多不同的属性,您可以使用这些属性来了解它们所处的当前状态。

dirty 将是一个布尔值,表示表单控件的值是否已更改,touched 也可能对您有用,让您知道该控件是否已被用户触摸。

onOrderActionBlur($event): any 
{
   this.orderAction= this.form.get('orderAction');

   if (this.orderAction.dirty) 
   {
     // control value has been modified 
   }
   else 
   {
     // control value has not been modified
   }
}

您可能不希望您的应用程序在用户有机会编辑表单之前显示错误。对脏和触摸的检查可以防止错误显示,直到用户执行以下两种操作之一:更改值,使控件变脏;或模糊表单控件元素,将控件设置为touched。

Documentation surrounding controls.

【讨论】:

  • 谢谢,这让我朝着正确的方向前进。
  • 很高兴为您提供帮助 :-)
猜你喜欢
  • 2018-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-23
  • 1970-01-01
相关资源
最近更新 更多